https://leetcode-cn.com/problems/implement-stack-using-queues/
class MyStack {
Deque<Integer> cur,pre;
/** Initialize your data structure here. */
public MyStack() {
cur = new LinkedList<>();
pre = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
pre.addLast(x);
while(!cur.isEmpty()) pre.addLast(cur.pollFirst());
while(!pre.isEmpty()) cur.addLast(pre.pollFirst());
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int res = cur.peekFirst();
cur.pollFirst();
return res;
}
/** Get the top element. */
public int top() {
return cur.peekFirst();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return cur.isEmpty();
}
}
用队列实现栈不能用上一题的思路,两个队列相互倒腾,因为队列是先进先出,就算把队列a的值倒腾到队列b,也不过是再造了一个队列a。
思路:
1.cur队列存储的是维护好的栈顺序。
2.每次push之前,先把元素存在备用pre队列头(此时pre为空),然后把cur的元素全都导到pre中,形成push的x在pre的头中,实现了后入先出
3.要维护push函数,就要在push函数最后把pre中的元素全都导回cur,保证每次调用push,pre都为空,cur为倒序的队列(相当于栈)
可以优化使用一个队列,cur.size知道cur队列的size,把队列的先进元素pollLast然后再addFirst,只留下cur队列中的最后一个元素不操作,让最后一个元素保持在cur队列的第一个,实现了cur队列的先进后出。