代码随想录算法训练营第十天|232.用栈实现队列、225.用队列实现栈

文章介绍了两种数据结构的实现方法:使用两个栈来模拟队列,以及用两个队列来模拟栈。在栈实现队列中,关键在于push时保持元素在stack1底部,pop和peek操作都在stack1进行。而在队列实现栈中,重点是通过将队列末尾元素移到front来模拟栈的出栈操作。
摘要由CSDN通过智能技术生成

题目链接:232.用栈实现队列

方法1:stack1、stack2,在push过程中保证每次都将元素压到stack1的底部,这样在pop或者查看front元素都仅需在stack1顶部执行操作即可。为了实现每次push时将元素压到stack1底部,每次push时将stack1中所有元素存放到stack2中,stack1压入指定元素,将stack2中元素重新存放如stack1。

class MyQueue {
public:
    MyQueue() {

    }
    
    void push(int x) {
        while(!stack1.empty()) {
            stack2.push(stack1.top());
            stack1.pop();
        }
        stack1.push(x);
        while(!stack2.empty()) {
            stack1.push(stack2.top());
            stack2.pop();
        }
    }
    
    int pop() {
        int top = stack1.top();
        stack1.pop();
        return top;
    }
    
    int peek() {
        return stack1.top();
    }
    
    bool empty() {
        return stack1.empty();
    }

private:
    stack<int> stack1, stack2;
};

方法2:stackIn、 stackOut。stackOut中是队列前部的几个元素,stackIn是队列尾部的几个元素。在pop过程中因为需要前部元素,如果stackOut中元素为空,需要将stackIn中元素存入。

class MyQueue {
public:
    MyQueue() {

    }
    
    void push(int x) {
        stackIn.push(x);
    }
    
    int pop() {
        if(stackOut.empty()) {
            while(!stackIn.empty()) {
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        int front = stackOut.top();
        stackOut.pop();
        return front;
    }
    
    int peek() {
        int front = pop();
        stackOut.push(front);
        return front;
    }
    
    bool empty() {
        return stackIn.empty() && stackOut.empty();
    }

private:
    stack<int> stackIn, stackOut;
};

题目链接:225.用队列实现栈

关键点在于出栈操作,队列只能将front元素pop,stack只能将back(top)元素pop,因此将队列末尾元素移动到front位置就能完成栈。

class MyStack {
public:
    MyStack() {

    }
    
    void push(int x) {
        _que.push(x);
    }
    
    int pop() {
        for(int i = 0; i < _que.size() - 1; i++) {
            _que.push(_que.front());
            _que.pop();
        }
        int top = _que.front();
        _que.pop();
        return top;
    }
    
    int top() {
        int result = pop();
        push(result);
        return result;
    }
    
    bool empty() {
        return _que.empty();
    }

private:
    queue<int> _que;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值