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

重点

  • 栈和队列是STL(C++标准库)里面的两个数据结构。
  • 栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。
  • 所以STL中栈往往不被归类为容器,而被归类为container adapter(容器适配器)。
  • 我们常用的SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构。
  • SGI STL中队列一样是以deque为缺省情况下的底部结构。
  • 在工业级别代码开发中,最忌讳的就是 实现一个类似的函数,直接把代码粘过来改一改就完事了。
  • 一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时在去弹出元素就是栈的顺序了。

刷题笔记

//232

class MyQueue {
public:
    stack<int> stIn; //定义一个栈
    stack<int> stOut;
    MyQueue() { 

    }

    void push(int x) {
        stIn.push(x); //栈的push()方法

    }
    
    int pop() {
        if(stOut.empty()){ //判断栈是否为空
            while(!stIn.empty()){
                stOut.push(stIn.top());//栈的top()
                stIn.pop();//栈的pop()
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }
    
    int peek() {
        if(stOut.empty()){
            while(!stIn.empty()){
                stOut.push(stIn.top());
                stIn.pop();
            }           
        }
        int result = stOut.top();
        return result;
    }
    
    bool empty() {
        return stIn.empty() && stOut.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();
 */

//225

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

    }
    
    void push(int x) {
        que1.push(x);//队列的push(),队尾加一个元素
    }
    
    int pop() {
        while(que1.size() > 1){
            int a = que1.front();//访问队列第一个元素
            que1.pop(); //删除队列第一个元素,没有返回值
            que2.push(a);
        }
        int result = que1.front();
        que1.pop();

        while(!que2.empty()){//队列判空,和栈一样
            int b = que2.front();
            que2.pop();
            que1.push(b);
        }
        return result;
    }
    
    int top() {
        int result = this->pop();
        que1.push(result);
        return result;
    }
    
    bool empty() {
        if(que1.empty()) return true;
        else return false;
    }
};

/**
 * 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();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值