Implement Stack using Queues leetcode

本文介绍了如何使用一个或两个队列来实现栈的基本操作:push、pop、top 和 empty。通过巧妙的设计,不仅可以减少所需的数据结构数量,还能保证操作效率。

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

 

不用多想,可以使用两个queue来实现,代码如下

耗时在pop上

class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        que1.push(x);
    }

    // Removes the element on top of the stack.
    void pop() {
        while (que1.size() > 1)
        {
            que2.push(que1.front());
            que1.pop();            
        }
        que1.pop();
        while (!que2.empty())
        {
            que1.push(que2.front());
            que2.pop();
        }
    }

    // Get the top element.
    int top() {
        return que1.back();
    }

    // Return whether the stack is empty.
    bool empty() {
        return que1.empty();
    }
private:
    queue<int> que1;
    queue<int> que2;
};

 

查看其它人的代码,发现居然可以使用一个queue来实现,实现思路非常巧妙,每一次push操作都将queue之前的元素都移到后面,使其保持栈的排序

如:

push 1

1

push 2

2 1

push 3

3 2 1

class Stack {
public:
    queue<int> que;
    // Push element x onto stack.
    void push(int x) {
        que.push(x);
        for (int i = 0; i<que.size() - 1; ++i) {
            que.push(que.front());
            que.pop();
        }
    }

    // Removes the element on top of the stack.
    void pop() {
        que.pop();
    }

    // Get the top element.
    int top() {
        return que.front();
    }

    // Return whether the stack is empty.
    bool empty() {
        return que.empty();
    }
};

 

转载于:https://www.cnblogs.com/sdlwlxf/p/5134649.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值