1囚玫、題目
Leetcode 225. Implement Stack using Queues
2悯搔、思路
始終保證隊列a為空约啊,新元素x添加到空隊列a中栋荸,x就始終在a的隊頭框咙。
再將另外一個隊列b中的數(shù)據(jù)依次加入到a中伸辟,a隊列里的元素就保持著先進(jìn)后出的性質(zhì)煤墙。
3梅惯、Java 代碼
class MyStack {
private Queue<Integer> a;//輸入隊列
private Queue<Integer> b;//輸出隊列
public MyStack() {
a = new LinkedList<>();
b = new LinkedList<>();
}
public void push(int x) {
a.offer(x);
// 將b隊列中元素全部轉(zhuǎn)給a隊列
while(!b.isEmpty())
a.offer(b.poll());
// 交換a和b,使得a隊列沒有在push()的時候始終為空隊列
Queue temp = a;
a = b;
b = temp;
}
public int pop() {
return b.poll();
}
public int top() {
return b.peek();
}
public boolean empty() {
return b.isEmpty();
}
}
參考文章:
https://leetcode.cn/problems/implement-stack-using-queues/comments/