leetcode刷题笔记——用队列实现栈

题目

用队列实现栈题目链接

题解

解法一 使用两个队列

核心在于push操作。使用两个队列q1、q2。q1为模拟栈的队列,q2为辅助队列。当push一个新元素x时,将x push到队列q2中,再将q1中的所有元素push到q2中,交换q1、q2。这样的话,新元素x就在q1的队列的第一位,对于push和pop操作,都是对新元素x进行操作。

class MyStack {
public:
    queue<int> q1;
    queue<int> q2;
    MyStack() {
        ;
    }
    
    void push(int x) {
        q2.push(x);
        while(!q1.empty())
        {
            q2.push(q1.front());
            q1.pop();
        }
        swap(q1,q2);
    }
    
    int pop() {
        int res = q1.front();
        q1.pop();
        return res;
    }
    
    int top() {
        return q1.front();
    }
    
    bool empty() {
        return q1.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();
 */

解法二 使用一个队列

核心在于push操作,当push一个新元素x时,将x push到队列q的末尾,再将队列q的前面的所有元素一次pop并push到队尾。这样的话,元素x来到队列第一个的位置,模拟出栈的结构。

class MyStack {
public:
    queue<int>  q;
    MyStack() {
        ;
    }
    
    void push(int x) {
        int size = q.size();
        q.push(x);
        for(int i=0;i<size;i++)
        {
            int res = q.front();
            q.pop();
            q.push(res);
        }
    }
    
    int pop() {
        int res = q.front();
        q.pop();
        return res;
    }
    
    int top() {
        return q.front();
    }
    
    bool empty() {
        return q.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();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值