使用两个栈实现一个队列

来源:互联网 发布:java开发监控系统 编辑:程序博客网 时间:2024/06/10 09:25

问题分析:

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、判断元素出栈合法性

原创粉丝点击