两个队列("先进先出")实现一个栈("后进先出")
//.h
#include<iostream>
using namespace std;
#include <queue>
#include<string>
template<class T>
class Stack
{
public:
Stack()
:_size(0)
{}
~Stack()
{}
void Push(T t);
void Pop();
T Top();
int Size();
protected:
queue<T> A;
queue<T> B;
int _size;
};
template<class T>
void Stack<T>::Push(T t)
{
A.push(t);
++_size;
}
template<class T>
void Stack<T>::Pop()
{
while(A.size()>1)
{
B.push(A.front());
A.pop();
}
A.pop();
while(B.size()!=0)
{
A.push(B.front());
B.pop();
}
--_size;
}
template<class T>
T Stack<T>::Top()
{
while(A.size()>1)
{
B.push(A.front());
A.pop();
}
T tmp=A.front();
B.push(A.front());
A.pop();
while(B.size()!=0)
{
A.push(B.front());
B.pop();
}
return tmp;
}
template<class T>
int Stack<T>::Size()
{
return _size;
}//.c
#include"StackQueue.h"
#include<iostream>
using namespace std;
#include<string>
void Test1()
{
Stack<int> s;
s.Push(1);
s.Push(2);
s.Push(3);
while(s.Size())
{
cout<<s.Top()<<" ";
s.Pop();
}
cout<<endl;
}
void Test2()
{
Stack<string> s;
s.Push("ld");
s.Push("wor");
s.Push(" ");
s.Push("llo");
s.Push("he");
while(s.Size())
{
cout<<s.Top();
s.Pop();
}
cout<<endl;
}
int main()
{
Test1();
// Test2();
return 0;
}本文出自 “花开彼岸” 博客,请务必保留此出处http://zxtong.blog.51cto.com/10697148/1730929
原文:http://zxtong.blog.51cto.com/10697148/1730929