您的位置:首页 > 其它

两个队列实现一个栈

2016-01-02 20:48 302 查看
两个队列("先进先出")实现一个栈("后进先出")

//.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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: