LeetCode232.用栈实现队列

本文介绍了如何利用两个栈来实现队列的基本功能,包括push、pop、peek和empty操作。关键在于push时将原栈元素逆序入栈,从而保持栈底元素为队首元素。这种方法的时间复杂度均为O(1),但空间复杂度为O(n),因为可能需要额外的栈存储所有元素。
摘要由CSDN通过智能技术生成

用栈实现队列

Problem: 232. 用栈实现队列

思路

现在有一个栈和队列,假如入栈的顺序和入队列的顺序相同。队列的大部分操作,如front(),和pop(),实际上就是每次对栈底的元素进行操作。由于栈只能对栈顶元素进行操作,我们需要使栈中元素的顺序和队列中元素的顺序相反。

解题方法

由于栈中的元素顺序和队列中元素的顺序相反,所以queue.front() == stack.top(), queue.empty() = stack.empty(), queue.pop() == stack.pop()。为了使栈中元素的顺序与队列中元素的顺序不同,所以我们在执行queue.push()的操作的时候需要在我们的逆序的栈的栈底加入新的元素,这里我使用了一个辅助栈来实现在栈底增加元素的需求。

复杂度

  • 时间复杂度:

O ( 1 ) O(1) O(1)

  • 空间复杂度:

O ( n ) O(n) O(n)

Code

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

class MyQueue {
public:
    stack<int> sta;
    MyQueue() {

    }
    
    void push(int x) {
        stack<int> tmp;
        while(!sta.empty()) {
            tmp.push(sta.top());
            sta.pop();
        }
        tmp.push(x);
        while(!tmp.empty()) {
            sta.push(tmp.top());
            tmp.pop();
        }
    }
    
    int pop() {
        int top = sta.top();
        sta.pop();
        return top;
    }
    
    int peek() {
        return sta.top();
    }
    
    bool empty() {
        return sta.empty();
    }
};

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值