代码随想录Day10:用栈实现队列,用队列实现栈

栈与队列

  • 队列是先进先出,栈是先进后出。
  • 栈和队列都是容器适配器。
  • 栈和队列是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。
  • 如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构。

std::stack的主要接口:

push(const value_type& value): 在栈顶添加元素。
pop(): 移除栈顶元素。
top(): 返回栈顶的元素。
empty(): 如果栈空则返回真,否则返回假。
size(): 返回栈中元素的数量。

std::queue的主要接口:

push(const value_type& value): 在队列尾部添加元素。
pop(): 移除队列首部的元素。
front(): 返回队列首部的元素。
back(): 返回队列尾部的元素。
empty(): 如果队列空则返回真,否则返回假。
size(): 返回队列中元素的数量。

用栈实现队列

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    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;
    }
    
    int peek() {
        int res = this->pop();
        stOut.push(res);
        return res;
    }
    
    bool empty() {
        if(stIn.empty() && stOut.empty()) return true;
        return false;
    }
};

用队列实现栈

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

    }
    
    void push(int x) {
        queInt.push(x);
        for(int i = 0; i < queInt.size() - 1; i++)
        {
            queInt.push(queInt.front());
            queInt.pop();
        }
    }
    
    int pop() {
            int res = queInt.front();
            queInt.pop();
            return res;
    }
    
    int top() {
        return queInt.front();
    }
    
    bool empty() {
        return queInt.empty();
    }
};
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值