LeetCode
用隊列實現棧
題目鏈接:225. 用隊列實現棧 - 力扣(LeetCode)
題目描述
請你僅使用兩個隊列實現一個后入先出(LIFO)的棧,并支持普通棧的全部四種操作(push
、top
、pop
和 empty
)。
實現 MyStack
類:
void push(int x)
將元素 x 壓入棧頂。int pop()
移除并返回棧頂元素。int top()
返回棧頂元素。boolean empty()
如果棧是空的,返回true
;否則,返回false
。
注意:
- 你只能使用隊列的基本操作 —— 也就是
push to back
、peek/pop from front
、size
和is empty
這些操作。 - 你所使用的語言也許不支持隊列。 你可以使用 list (列表)或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。
示例:
輸入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 2, 2, false]解釋:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
提示:
1 <= x <= 9
- 最多調用
100
次push
、pop
、top
和empty
- 每次調用
pop
和top
都保證棧不為空
**進階:**你能否僅用一個隊列來實現棧。
思路
棧:后進先出,元素從頂端入棧,從頂端出棧
隊列:先進先出,元素從后端入列,從前端出列
代碼
C++
class MyStack {
public:queue<int> queue1;queue<int> queue2;MyStack() {}void push(int x) {queue2.push(x); // 將元素入隊到queue2while(!queue1.empty()){ // 將queue1的全部元素依次出隊并入列到queue2queue2.push(queue1.front());queue1.pop();}swap(queue1,queue2);}int pop() {int r = queue1.front();queue1.pop();return r;}int top() {int r = queue1.front();return r;}bool empty() {return queue1.empty();}
};/*** 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();* bool param_4 = obj->empty();*/
Java
class MyStack {Queue<Integer> queue1;Queue<Integer> queue2;Queue<Integer> temp;public MyStack() {queue1 = new LinkedList<Integer>();queue2 = new LinkedList<Integer>();}public void push(int x) {queue2.offer(x);while(!queue1.isEmpty()){queue2.offer(queue1.poll());}temp = queue1;queue1 = queue2;queue2 = temp;}public int pop() {return queue1.poll();}public int top() {return queue1.peek();}public boolean empty() {return queue1.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();*/