使用两个栈实现一个队列

问题分析:

push:直接将元素push到_s1即可;
pop:在进行pop时,队列是先进先出,栈是先进后出。故可以利用_s2,当_s2为空时,将_s1中的数据全都移动到_s2中,此时就可以实现先进先出。
**注意:**
        只有当_s2为空,将_s1的数据移动到_s2

场景一:_s2 为空

第一次pop

场景二:_s2不为空,_s1不为空

_s2不为空,_s1不为空

代码部分:

#pragma once
#include<iostream>
using namespace std;

#include<assert.h>
#include<stack>

class Queue
{
public:
    void Push(const int x)
    {
        _s1.push(x);
    }

    void Pop()
    {
        assert(!Empty());
        if (!_s2.empty())
        {
            _s2.pop();
            return;
        }
        //_s2为空,将_s1的数据移动到_s2
        while (!_s1.empty())
        {
            int tmp = _s1.top();
            _s1.pop();
            _s2.push(tmp);
        }
        _s2.pop();
    }

    int Front()
    {
        assert(!Empty());
        if (!_s2.empty())
            return _s2.top();
        while (!_s1.empty())
        {
            int tmp = _s1.top();
            _s1.pop();
            _s2.push(tmp);
        }
        return _s2.top();
    }

    bool Empty()
    {
        return _s1.empty() && _s2.empty();
    }

    size_t Size()
    {
        return _s1.size() + _s2.size();
    }
protected:
    stack<int> _s1;
    stack<int> _s2;
};

测试部分:

void TestQueue()
{
    Queue q;
    q.Push(1);
    q.Push(2);
    q.Push(3);
    q.Push(4);
    q.Push(5);
    cout <<"Front?"<< q.Front() << endl;
    cout << "Size?" << q.Size() << endl;
    cout << "Empty?" << q.Empty() << endl;

    q.Pop();
    q.Pop();
    q.Pop();
    q.Pop();
    cout << "Front?" << q.Front() << endl;
    cout << "Size?" << q.Size() << endl;
    cout << "Empty?" << q.Empty() << endl;

    q.Pop();
    q.Pop();
    q.Pop();
    cout << "Front?" << q.Front() << endl;
    cout << "Size?" << q.Size() << endl;
    cout << "Empty?" << q.Empty() << endl;
}

本人目前也正处于学习中,如果有考虑不周或者错误之处,请您谅解和指出,便于咱们的共同学习和进步!!!

常见栈和队列面试题
1、实现一个栈,push,pop,求栈中最小元素,时间复杂度O(1)
2、使用两个队列实现一个栈
3、利用一个数组实现两个栈
4、判断元素出栈合法性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值