解释: 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
Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>();
/** * Initialize your data structure here. */ publicMyQueue(){
}
/** * 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(){ while (!stack1.empty()) { stack2.push(stack1.pop()); } int result = stack2.pop(); while (!stack2.empty()) { stack1.push(stack2.pop()); } return result; }
/** * Get the front element. */ publicintpeek(){ while (!stack1.empty()) { stack2.push(stack1.pop()); } int result = stack2.peek(); while (!stack2.empty()) { stack1.push(stack2.pop()); } return result; }
/** * Returns whether the queue is empty. */ publicbooleanempty(){ return stack1.empty(); } }