标签:
栈s1和栈s2,栈s1专门为入队,栈s2专门为出队。
入队:
出队:
代码实现如下:
#include <iostream>
#include <stack>
using namespace std;
template <class T>
struct Myqueue{
T front()
{
if(s2.size()==0)
{
if(s1.size()==0)
{
cout<<"队列为空"<<endl;
return 0;
}
while(s1.size()>0)
{
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
void pop()
{
if(s1.size()==0 && s2.size()==0)
{
cout<<"队列为空"<<endl;
}
while(s1.size()>0)
{
s2.push(s1.top());
s1.pop();
}
s2.pop();
}
void push(T &t)
{
if(s1.size()==0)
{
while(s2.size()>0)
{
s1.push(s2.top());
s2.pop();
}
}
s1.push(t);
}
stack<T> s1;
stack<T> s2;
};
int main(void)
{
Myqueue<int> myqueue;
int flag;
int num;
int i=0;
for(i=0;i<10;i++)
myqueue.push(i);
for(i=0;i<10;i++)
{
cout<<myqueue.front()<<" ";
myqueue.pop();
}
cout<<endl;
while(1)
{
cout<<"请输入要执行的操作,入队或者出队,1为入队,2
为出队,3为打印队头,0为退出"<<endl;
cin>>flag;
if(flag==1)
{
cout<<"请输入要增加的结点的值"<<endl;
cin>>num;
myqueue.push(num);
}
else if(flag==2)
{
myqueue.pop();
}
else if(flag==3)
cout<<"队头结点为:"<<myqueue.front()<<endl;
else
break;
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/longzhongren/p/4419030.html