leetcode 232:用栈实现队列

本文介绍了一种使用两个栈来实现队列数据结构的方法。通过将push操作的元素首先存入一个栈,再将该栈的所有元素转移至另一个栈,以此达到队列先进先出的操作特性。文章详细阐述了push、pop、peek和empty等队列关键操作的具体实现。

题目:

算法思想:用两个栈来维护,把push的元素先放入一个栈中,这样操作和队列刚好是相反的,push完后把栈的所有元素放入另一个栈中,这样操作的顺序就和队列一致了。

 

代码:

    stack<int> s;
    stack<int> tmp_s;
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        int size = s.size();
        for(int i = 0;i < size;i++)
        {
            int tmp = s.top();
            tmp_s.push(tmp);
            s.pop();
        }
        tmp_s.push(x);
        size = tmp_s.size();
        for(int i = 0;i < size;i++)
        {
            int tmp = tmp_s.top();
            s.push(tmp);
            tmp_s.pop();
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int tmp = s.top();
        s.pop();
        return tmp;
    }
    
    /** Get the front element. */
    int peek() {
        return s.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        if(s.size() == 0)
            return true;
        return false;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值