LeetCode | Implement Queue using Stacks

在这里插入图片描述

题目解析
题目要求我们用栈来实现队列的基本操作:push(),pop(),peek()和empty()。

思路
做题目前得先了解栈的基本找操作,为了实现队列的操作,我使用了两个栈来模拟队列。
要放如元素时,直接把元素放进栈a中,
要删除元素时,首先判断栈a是否时空的,诺不是,在判断栈b是否有元素,如果同时满足栈a不空且栈b为空则将栈a的源素从栈顶开始搬进栈b,在删除b的栈顶元素。反之则直接删除栈b的栈顶元素。
查找队列头元素时与删除同理。
判断队列是否为空时,之需先判断栈a和b是否为空,时则返回true否则返回false。

代码

class MyQueue {
    stack<int> a;
    stack<int> b;
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        a.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int i;
        if(a.empty()==false&&b.empty()==true){
            while(a.empty()==false){
                i=a.top();
                a.pop();
                b.push(i);
            }
        }
        i=b.top();
        
        b.pop();
        return i;
    }
    
    /** Get the front element. */
    int peek() {
        int i;
        if(a.empty()==false&&b.empty()==true){
            while(a.empty()==false){
                i=a.top();
                a.pop();
                b.push(i);
            }
        }
        return b.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        if(a.empty()==false){
            return false;
        }
        if(b.empty()==false){
            return false;
        }
        else 
            return true;
    }
};

结果
在这里插入图片描述
小结
首先要对栈有所了解,同过两个栈来模拟队列的想法还是比较容易想到的,在完成代码时需要考虑什么时候将a中的元素搬进b里,明白了这个其他就没什么难度了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值