代码随想录-栈和队列01 232.用栈实现队列&225. 用队列实现栈

本篇题目

● 232.用栈实现队列
● 225. 用队列实现栈

232.用栈实现队列

232.用栈实现队列
本篇需要了解栈和容器的基本概念及实现原理。
本题实现队列,可以使用两个栈来模拟实现队列的接口。

class MyQueue2 {
public:
    MyQueue2() {

    }
    // 在队列末尾加入元素
    void push(int x) {
        _stack.push(x);
    }
    // 队头元素弹出并返回
    int pop() {
        while (!_stack.empty()) {
            int val = _stack.top();
            _stack.pop();
            _tmpStack.push(val);
        }
        int ret = -1;
        if (!_tmpStack.empty()) {
            ret = _tmpStack.top();
            _tmpStack.pop();
        }
        while (!_tmpStack.empty()) {
            int val = _tmpStack.top();
            _tmpStack.pop();
            _stack.push(val);
        }
        return ret;
    }
    // 队头元素返回
    int peek() {
        while (!_stack.empty()) {
            int val = _stack.top();
            _stack.pop();
            _tmpStack.push(val);
        }
        int ret = -1;
        if (!_tmpStack.empty())
            ret = _tmpStack.top();
        while (!_tmpStack.empty()) {
            int val = _tmpStack.top();
            _tmpStack.pop();
            _stack.push(val);
        }
        return ret;
    }
    // 队列是否为空
    bool empty() {
        return _stack.empty();
    }
private:
    stack<int> _stack;
    stack<int> _tmpStack;
};

225. 用队列实现栈

225. 用队列实现栈

// 最好画图来验证是否正确
// 栈的弹出元素我的思路是错误的
// 相当于弹出了栈底元素
class MyStack {
public:
    void push(int x) {
        _queue.push(x);
	}
	int pop() {
        // 弹出_queue除了最后一个元素前的所有元素
        while (_queue.size() > 1){
            int val  = _queue.front();
            _queue.pop();
			_tmpQueue.push(val);
		}
        // 获取最后一个栈顶元素
        int ret = -1;
        if (!_queue.empty()) {
            ret = _queue.front();
            _queue.pop();
        }
        // 重新还原到_queue
		while (!_tmpQueue.empty()) {
            int val = _tmpQueue.front();
            _tmpQueue.pop();
			_queue.push(val);
		}
		return ret;
	}
	int top() {
		return _queue.back();
	}
	bool empty() {
		return _queue.empty();
	}
	int size() {
		return _queue.size();
	}
	
private:
	queue<int> _queue;
	queue<int> _tmpQueue;
	
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

love_0_love

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

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

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

打赏作者

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

抵扣说明:

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

余额充值