方法一. 使用两个单端队列
思路是让 q1
的元素永远跟 我们的 Stack
保持一致.
push
的时候 使用辅助队列 q2
:
1. 先把元素加入 q2
中
2. 之后再把 q1
中的元素依次加入 q2
中
3. 在交换 q1
q2
使得其定义保持一致
class MyStack {
private Queue<Integer> q1; // Same elements as our stack
private Queue<Integer> q2; // Auxiliary Queue.
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q2.offer(x);
while (!q1.isEmpty()) {
q2.offer(q1.poll());
}
Queue<Integer> tempQ;
tempQ = q1;
q1 = q2;
q2 = tempQ;
}
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
方法二. 使用一个双端队列
思路是 push
就加入队尾
pop
就把队头的元素全部放在队尾,留最后一个元素再 pop
top
是队尾的元素(最后入队)
class MyStack {
private Deque<Integer> q1;
public MyStack() {
q1 = new ArrayDeque<>();
}
public void push(int x) {
q1.addLast(x);
}
public int pop() {
int size = q1.size();
size--;
while(size-- > 0) {
q1.addLast(q1.pollFirst());
}
return q1.pollFirst();
}
public int top() {
return q1.peekLast();
}
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/