#include <iostream>
#include <stack>
using namespace std;
template<class T>
class Queue
{
stack<T> s1;
stack<T> s2;
public:
bool empty_queue(void) //判断队空
{
return s1.empty() && s2.empty();
}
void push_queue(T val) //入队,由于是链式栈,无栈满情况
{
s1.push(val);
cout << val << endl;
}
bool pop_queue(void) //出队
{
if(s2.empty())
{
if(s1.empty()) return false;
while(!s1.empty())
{
T top=s1.top();
s1.pop();
s2.push(top);
}
}
s2.pop();
return true;
}
bool get_front(T& val) //获取队头元素
{
if(s2.empty())
{
if(s1.empty()) return false;
while(!s1.empty())
{
T top=s1.top();
s1.pop();
s2.push(top);
}
}
val=s2.top();
return true;
}
};
int main(int argc,const char* argv[])
{
Queue<int> queue;
for(int i=0;i<10;i++)
{
queue.push_queue(i);
}
cout << "---------"<<endl;
for(int i=0;i<10;i++)
{
int val=0;
queue.get_front(val);
cout << val <<endl;
queue.pop_queue();
}
}
代码结果如下:
入队思路:(栈1入)
1、由于栈容器底层是链式栈实现,所以不需要判断s1是否栈满情况,直接入栈1
2、如果用顺序栈实现
a、如果栈s1满,并且栈s2不空,入栈失败(入队失败)
b、如果栈s1满,并且栈s2空,将栈s1所有数据入到栈2,入栈1
c、如果栈s1不满,入栈1
出队思路:(栈2出)
无论是链式栈还是顺序栈实现,出队时都需要判断是否栈空
a、如果栈2空,并且栈1空,出栈失败(出队失败)
b、如果栈2空,栈1不为空,将栈s1所有数据入到栈2,出栈2
c、如果栈2不空,出栈2