利用两个栈来实现队列的操作。
代码如下所示
#include <iostream>
#include <stack>
using namespace std;
template<class T>
class QueueFromStack{
private:
stack<T> s1;
stack<T> s2;
public:
// use reference instead of variable pass
void push(const T& value);
T pop();
};
template<class T>
void QueueFromStack<T>:: push(const T& value){
s1.push(value);
}
template<class T>
T QueueFromStack<T>:: pop(){
if(!s2.empty()){
T tmp = s2.top();
s2.pop();
return tmp;
}else if( !s1.empty() ){
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
T tmp = s2.top();
s2.pop();
return tmp;
}else // this is very important
throw new exception();
}
int main(){
int array[10]={1,2,3,4,5,6,7,8,9,0};
QueueFromStack<int> *queue = new QueueFromStack<int>();
for(int i = 0 ; i < 10; ++i){
queue->push(array[i]);
}
for(int i = 0 ; i < 10; ++i){
cout<<queue->pop()<<" ";
}
cout<<endl;
delete queue;
system("PAUSE");
return 0;
}
利用两个队列来实现栈的操作
#include <iostream>
#include <queue>
using namespace std;
template<class T>
class StackFromQueue{
private:
queue<T> q1;
queue<T> q2;
T pop(queue<T>& q1, queue<T>& q2);
public:
void push(const T& value);
T pop();
};
template<class T>
T StackFromQueue<T>::pop(queue<T>& q1, queue<T>& q2){
while(1!=q2.size()){
q1.push(q2.front());
q2.pop();
}
T tmp = q2.front();
q2.pop();
return tmp;
}
template<class T>
void StackFromQueue<T>::push(const T& value){
if(!q1.empty())
q1.push(value);
else
q2.push(value);
}
template<class T>
T StackFromQueue<T>::pop(){
if(q1.empty() && q2.empty())
throw new exception();
if(q1.empty())
return pop(q1,q2);
else
return pop(q2,q1);
}
int main(){
StackFromQueue<int> stack;
for(int i = 0 ; i < 10; ++i)
stack.push(i);
for(int i = 0 ; i < 10 ; ++i)
cout<<stack.pop()<<" ";
cout<<endl;
system("PAUSE");
return 0;
}