leetcode刷题 用堆栈实现队列 C++

本文介绍了如何使用C++通过堆栈来实现队列的功能,包括push、pop、peek和empty操作。核心思路是利用两个堆栈,一个用于push和暂时存储,另一个用于pop。当需要pop时,若输出堆栈为空,则将输入堆栈的所有元素依次转移到输出堆栈,确保队列的FIFO特性。

leetcode刷题 用堆栈实现队列 C++

问题描述

使用栈实现队列的下列操作:

push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。

思路

堆栈操作时先入后出,为了实现队列的先入先出操作,就需要将先入先出的堆栈进行存储循序的颠倒,所以需要两个堆栈单元来实现队列操作,定义两个堆栈分别为输入堆栈,对应于push操作,输出堆栈,对应于pop操作。要想使得push的数据在堆栈底部,就需要将原堆栈清空保存在一个堆栈缓冲区,push在堆栈底部,然后再将缓存区的数据库压入新的堆栈。

代码

class MyQueue {
public:
    /** Initialize your data structure here. */
         stack<int> instack;
        stack<int> outstack;
    MyQueue() {
       

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        
        while(!outstack.empty())
        {
            instack.push(outstack.top());
            outstack.pop();
        }
        outstack.push(x);
        while(!instack.empty())
        {
            outstack.push(instack.top());
            instack.pop();
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
       int a = outstack.top();
       outstack.pop();
        return a;
        
    }
    
    /** Get the front element. */
    int peek() {
        return outstack.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return outstack.empty();
    }
};

/**
 * 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();
 */
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值