解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false
/** Initialize your data structure here. */ publicMyQueue(){ stack1 = new Stack<>(); // 负责进栈 stack2 = new Stack<>(); // 负责出栈 } /** Push element x to the back of queue. */ publicvoidpush(int x){ stack1.push(x); } /** Removes the element from in front of queue and returns that element. */ publicintpop(){ dumpStack1(); return stack2.pop(); } /** Get the front element. */ publicintpeek(){ dumpStack1(); return stack2.peek(); } /** Returns whether the queue is empty. */ publicbooleanempty(){ return stack1.isEmpty() && stack2.isEmpty(); }
// 如果stack2为空,那么将stack1中的元素全部放到stack2中 privatevoiddumpStack1(){ if (stack2.isEmpty()){ while (!stack1.isEmpty()){ stack2.push(stack1.pop()); } } } }