/* * 232. Implement Queue using Stacks * 2016-6-14 by Mingyang * 只用两个stack,每次只用改push得程序,只要这个每次进来一个,就把所有的依次弹入另一个,加入值以后依次弹回来 * 这里跟implement stack using queue不一样,不用换queue换来换去的哈 */ class MyQueue { Stack<Integer> queue = new Stack<Integer>(); Stack<Integer> temp = new Stack<Integer>(); // Push element x to the back of queue. public void push(int x) { while (!queue.empty()) { temp.push(queue.pop()); } queue.push(x); while (!temp.empty()) { queue.push(temp.pop()); } } // Removes the element from in front of queue. public void pop() { queue.pop(); } // Get the front element. public int peek() { return queue.peek(); } // Return whether the queue is empty. public boolean empty() { return queue.empty(); } }