leetcode 225. Implement Stack using Queues (用队列实现栈)

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

Implement the MyStack class:

void push(int x) Pushes element x to the top of the stack.
int pop() Removes the element on the top of the stack and returns it.
int top() Returns the element on the top of the stack.
boolean empty() Returns true if the stack is empty, false otherwise.
Notes:

You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue’s standard operations.

Example 1:

Input
[“MyStack”, “push”, “push”, “top”, “pop”, “empty”]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]

Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

用两个队列实现一个栈。
只能用队列的现有操作(先入先出)。

思路:
队列的现有操作是先入先出,而栈是后入先出,

栈的pop操作时,要取queue最后进的数字,而queue本身的pop操作则是取出最先压进的数字,
要取最后一个数字则需要把前面所有的数字都取出来,才能取出最后的。
然后再把前面取出的所有数字存回去。

而这里用另外一个queue保存取出的所有数字(除了最后一个),然后不必再存回去,只需要交换两个队列即可。

top操作是返回栈顶的数字,但不删除,
所以存入数字时要记录最后存入的数字,
pop时要记录倒数第2个取出的数字(因为最后一个已删除)。

Java实现上要注意Queue是接口,不能instance化,使用时用
在这里插入图片描述
这里使用ArrayDeque,也可用LinkedList。

class MyStack {
    Queue<Integer> q1, q2;
    int top = 0;

    public MyStack() {
        q1 = new ArrayDeque<Integer>();
        q2 = new ArrayDeque<Integer>();
    }
    
    public void push(int x) {
        q1.offer(x);
        top = x;
    }
    
    public int pop() {
        while(q1.size() > 1) {
            top = q1.poll();
            q2.offer(top);
        }
        int res = q1.poll();
        Queue<Integer> tmp = q1;
        q1 = q2;
        q2 = tmp;
        return res;
    }
    
    public int top() {
        return top;
    }
    
    public boolean empty() {
        return (q1.size() == 0);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值