队列是先进先出,而栈是先进后出,要想实现用两个队列完成栈的功能,可通过如下代码实现:
#include<iostream>
#include<queue>
#include<exception>
using namespace std;
template<typename T> //或者用template<class T>
class CStack{
public:
CStack(void);
~CStack(void);
void appendTail(const T &node);
T deleteTail();
private:
queue<T> queue1;
queue<T> queue2;
};
template<typename T> CStack<T>::CStack(void){
}
template<typename T> CStack<T>::~CStack(void){
}
template<typename T>
void CStack<T>::appendTail(const T &node){ //注意类名后要加<T>
if(!queue1.empty())
queue1.push(node);
else
queue2.push(node);
}
template<typename T>
T CStack<T>::deleteTail(){
T res;
if( (queue1.size() == 0) && (queue2.size() == 0) ){
try{
throw "栈为空!";
}
catch(char const *s){
cout<<"出现异常: "<<s<<endl;
}
}
while(queue1.size() > 1){
queue2.push(queue1.front());
queue1.pop();
}
if(queue1.size() == 1){
res = queue1.front();
queue1.pop();
return res;
}
while(queue2.size() > 1){
queue1.push(queue2.front());
queue2.pop();
}
if(queue2.size() == 1){
res = queue2.front();
queue2.pop();
return res;
}
}
int main(){
CStack<int> myStack;
myStack.appendTail(173);
myStack.appendTail(3);
myStack.appendTail(130);
cout<<myStack.deleteTail()<<endl;
myStack.appendTail(14);
cout<<myStack.deleteTail()<<endl;
cout<<myStack.deleteTail()<<endl;
cout<<myStack.deleteTail()<<endl;
cout<<myStack.deleteTail()<<endl;
return 0;
}
运行结果如下: