#include <iostream>
#include <stack>
using namespace std;
// 用两个stack实现一个queue, 以int类型为例吧
class MyQueque
{
private:
stack<int> s1; // s1负责入队
stack<int> s2; // s2负责出队
public:
// 入队
void push(int x)
{
s1.push(x);
}
// 出队
void pop()
{
if(!s2.empty())
{
s2.pop();
}
else
{
while(!s1.empty())
{
int tmp = s1.top();
s1.pop();
s2.push(tmp);
}
s2.pop();
}
}
// 取头
int front()
{
if(!s2.empty())
{
return s2.top();
}
while(!s1.empty())
{
int tmp = s1.top();
s1.pop();
s2.push(tmp);
}
return s2.top();
}
// 取尾
int back()
{
if(!s1.empty())
{
return s1.top();
}
while(!s2.empty())
{
int tmp = s2.top();
s2.pop();
s1.push(tmp);
}
return s1.top();
}
// 求大小
int size()
{
return s1.size() + s2.size();
}
// 判断是否为空
bool empty()
{
if(s1.empty() && s2.empty())
{
return true;
}
return false;
}
};
int main()
{
{
MyQueque que;
que.push(1);
que.push(2);
que.push(3);
que.push(4);
que.push(5);
while(!que.empty())
{
cout << que.front() << endl;
que.pop();
}
cout << "-------------------" << endl;
}
{
MyQueque que;
que.push(1);
que.push(2);
que.push(3);
que.push(4);
que.push(5);
while(!que.empty())
{
cout << que.size() << endl;
que.pop();
}
cout << "-------------------" << endl;
}
{
MyQueque que;
que.push(1);
que.push(2);
que.push(3);
que.pop();
que.pop();
que.push(4);
que.push(5);
while(!que.empty())
{
cout << que.front() << endl;
que.pop();
}
cout << "-------------------" << endl;
}
return 0;
}
两个栈来实现一个队列的C++代码
最新推荐文章于 2021-02-15 20:38:55 发布