0
点赞
收藏
分享

微信扫一扫

两个队列实现一个栈

千妈小语 2022-09-02 阅读 93



//两个队列实现一个栈
#include<iostream>
using namespace std;
#include<queue>
#include<assert.h>
template<class T>
class Stack
{
public:
//插入
void Push(const T& x)
{
if (!_q2.empty())//如果不为空,插入到q2
_q2.push(x);
else//若q2为空,插入到q1中
_q1.push(x);
}
void Pop()//出栈,两个队列来回倒换数据
{
if (!_q1.empty())//如果q1不为空
{//就把q1中的数据全部放入到q2中,只留下最后一个
while (_q1.size() != 1)
{
_q2.push(_q1.front());
_q1.pop();
}
_q1.pop();//出栈
}
else//q1为空
{//就把q2中的数据全部放入到q1中,只留下最后一个
while (_q2.size() != 1)
{
_q1.push(_q2.front());
_q2.pop();
}
_q2.pop();
}
}
T& Top()//取栈顶元素
{//q1不为空,就返回q1.back
if (!_q1.empty())
{
return _q1.back();
}
else//否则返回q2.back
return _q2.back();
}
protected:
queue<T> _q1;
queue<T> _q2;
};

void Test1()
{
Stack<int> s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
s1.Push(5);
s1.Pop();
cout << s1.Top() << endl;//4
s1.Pop();
cout << s1.Top() << endl;//3
//cout << s1.Size() << endl;

s1.Push(6);
cout << s1.Top() << endl;//6
s1.Pop();
cout << s1.Top() << endl;//3
s1.Push(7);
cout << s1.Top() << endl;//7
s1.Pop();
s1.Pop();
s1.Pop();
cout << s1.Top() << endl;//1
}
int main()
{
Test1();
system("pause");
return 0;
}



举报

相关推荐

0 条评论