class MyQueue{
int num;
Deque<Integer> sta1, sta2;//使用双端队列来模拟栈
/** Initialize your data structure here. */
public MyQueue() {
sta1 = new LinkedList<>();
sta2 = new LinkedList<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
while(!sta1.isEmpty()){
sta2.push(sta1.pop());
}
sta1.push(x);
while(!sta2.isEmpty()){
sta1.push(sta2.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return sta1.pop();
}
/** Get the front element. */
public int peek() {
return sta1.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return sta1.isEmpty();
}
}
/**
* 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();
*/
class MyQueue{
int num;
Deque<Integer> insta, outsta;//使用双端队列来模拟栈
/** Initialize your data structure here. */
public MyQueue() {
insta = new LinkedList<>();
outsta = new LinkedList<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
insta.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(outsta.isEmpty()){
while(!insta.isEmpty()){
outsta.push(insta.pop());
}
}
return outsta.pop();
}
/** Get the front element. */
public int peek() {
if(outsta.isEmpty()){
while(!insta.isEmpty()){
outsta.push(insta.pop());
}
}
return outsta.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return outsta.isEmpty() && insta.isEmpty();
}
}
/**
* 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();
*/
原文:https://www.cnblogs.com/GarrettWale/p/14496322.html