标签:anti 入栈 java integer 机智 cal push str native
Implement the following operations of a queue using stacks.
push to top, peek/pop from top, size, and is empty operations are valid.public class MyQueue {
Stack<Integer> stack;
Stack<Integer> queue;
/** Initialize your data structure here. */
public MyQueue() {
stack = new Stack<Integer>();
queue = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (queue.empty()) {
while (!stack.empty()) {
queue.push(stack.pop());
}
}
return queue.pop();
}
/** Get the front element. */
public int peek() {
if (queue.empty()) {
while (!stack.empty()) {
queue.push(stack.pop());
}
}
return queue.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
if (stack.empty() && queue.empty()) {
return true;
} else {
return false;
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
232. Implement Queue using Stacks
标签:anti 入栈 java integer 机智 cal push str native
原文地址:http://www.cnblogs.com/yuchenkit/p/7173070.html