第十天 | 232.用栈实现队列 225.用队列实现栈

文章讨论了如何使用两个栈分别实现队列(MyQueue)和栈(MyStack)的功能,包括push、pop、top和empty方法的代码实现。作者关注的是代码逻辑和语言表达,尤其是在模拟队列操作时遇到的问题和解决方案。
摘要由CSDN通过智能技术生成

题目:232.用栈实现队列

尝试解答:之前做过,在逻辑上没有太大的问题,此次刷题要更注重代码语言。自己还写不出代码,需要看题解。

两个栈来模拟,一个进栈,一个出栈。

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;

    /** Initialize your data structure here. */
    MyQueue() {
        //这个函数是干啥用的?
    }
    
    void push(int x) {
        stIn.push(x);
    }
    
    int pop() {
        if(stOut.empty()){
            while(!stIn.empty()){
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
        //如果stOut里面存有数据,那么队列最开头的元素就是stOut.top()
    }
    
    int peek() {
        if(!stOut.empty()){
            return stOut.top();
        }else{
            while(!stIn.empty()){
                stOut.push(stIn.top());
                stIn.pop();
            }
            return stOut.top();
        }
    }
    
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};

题目:225.用队列实现栈

这道题不想上面的题,之前做完印象已经不深了。

尝试解答写下如下代码,在pop和top有问题。

class MyStack {
public:
    queue<int> que;
    MyStack() {

    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        int count = que.size() - 1;
        for(int i = 1; i <= count; i++){
            que.push(que.front());
            que.pop();
        }
        int result = que.front();
        que.pop();
        return result;
    }
    
    int top() {
        // int count = que.size() - 1;
        // for(int i = 1; i <= count; i++){       //此处计数循环出错,i应该从1开始
        //     que.push(que.front());
        //     que.pop();
        // }
        // int result = que.front();
        // return result;

        return que.back();
    }
    
    bool empty() {
        return que.empty();
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值