Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
代码如下:
class MyQueue { // Push element x to the back of queue. Stack<Integer>stack=new Stack<Integer>(); public void push(int x) { if(stack.empty()) stack.push(x); else{ Stack<Integer> ss=new Stack<Integer>(); while(!stack.empty()) { ss.push(stack.peek()); stack.pop(); } stack.push(x); while(!ss.empty()) { stack.push(ss.peek()); ss.pop(); } } } // Removes the element from in front of queue. public void pop() { stack.pop(); } // Get the front element. public int peek() { return stack.peek(); } // Return whether the queue is empty. public boolean empty() { return stack.empty(); } }