第十天打卡:stack & queue还挺难

文章介绍了如何在C++中使用Stack和Queue来实现其他数据结构。具体包括用两个Stack实现Queue,以及用Queue实现Stack。关键操作如push、pop、peek和empty都在各自的实现中得到了详细解释。

C++中的Stack:

  1. 不支持iterator

  2. 不是container,而是container adapter

  3. 底层实现:vector, deque, list都可以,比如:

     std::stack<int, std::vector<int> > third;  // 使用vector为底层容器的栈
    

1.Implement Queue using Stacks
没想出来的题,stack和queue的题就是我的克星…

class MyQueue {
private:
    stack<int> instack, outstack;
    void revert(){
        while(!instack.empty()){
            outstack.push(instack.top());
            instack.pop();
        }
    }

public:
    MyQueue() {}
    
    void push(int x) {
        instack.push(x);
    }
    
    int pop() {
        if(outstack.empty()){
            revert();
        }
        int x = outstack.top();
        outstack.pop();
        return x;
    }
    
    int peek() {
        if(outstack.empty()){
            revert();
        }
        return outstack.top();
    }
    
    bool empty() {
        return instack.empty() && outstack.empty();
    }
};

2.Implement Stack using Queues

过年了有点想摆烂,用一个queue的办法不想想了。简单来讲,就是把新元素加到queue的尾部,大差不离。

class MyStack {
private: 
    queue<int> q1, q2;
    void reload(){
        while(!q2.empty()){
            q1.push(q2.front());
            q2.pop();
        }
    }

public:
    MyStack() {}
    
    void push(int x) {
        q1.push(x);
    }
    
    int pop() {
        int x;
        while(!q1.empty()){
            x = q1.front();
            q1.pop();
            if(!q1.empty()) q2.push(x);
        }
        reload();
        return x;
    }
    
    int top() {
        int x = pop();
        q1.push(x);
        return x;
    } 
    
    bool empty() {
        return q1.empty();
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值