Day:10 第五章 栈与队列part01 ● 232.用栈实现队列● 225. 用队列实现栈

今日任务:
● 理论基础
● 232.用栈实现队列
● 225. 用队列实现栈

 232.用栈实现队列

. - 力扣(LeetCode) 

 stack<int> stIn;    //初始
 stack<int> stOut;   //辅助

功能:push:加入的一律到 stIn (套壳函数)

         pop:在stOut进行

        peek:利用pop,再push 

        empty:两个栈不同时空。

class MyQueue {
public:
    stack<int> stIn;    //初始
    stack<int> stOut;   //辅助
    /** Initialize your data structure here. */
    MyQueue() { //默认构造

    }
    /** Push element x to the back of queue. */
    void push(int x) {
        stIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
        if (stOut.empty()) {
            // 从stIn导入数据直到stIn为空
            while(!stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }

    /** Get the front element. */
    int peek() { //弹出去,再收回来  peek 利用pop
        int res = this->pop(); // 直接使用已有的pop函数
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};
  • 时间复杂度: push和empty为O(1), pop和peek为O(n)
  • 空间复杂度: O(n)

 225. 用队列实现栈 

一个队列实现了栈:每次加入元素:1.加入X

                                                           2.一直弹出,一直加入元素! 

class MyStack {
public:
    queue<int>q;
    MyStack() {
    }
    
    void push(int x) {
        int n = q.size();
        q.push(x);
        for (int i = 0; i < n; i++) { //先放入X 边弹出,边加入已有元素!
            q.push(q.front());
            q.pop();
        }


    }
    
    int pop() {
        int r = q.front(); //队列stl 与stack一致!
        q.pop();
        return r;
    }
    
    int top() {
        int r = q.front();
        return r;
    }
    
    bool empty() {
        return q.empty();
    }
};

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

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

计算机视觉入门

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值