您的位置:首页 > 其它

使用模板类,实现用两个栈模拟队列的功能

2013-07-22 11:29 267 查看
// 使用模板类,实现用两个栈模拟队列的功能

#include <stdlib.h>

#include <iostream>

#include <stack>

using namespace std;

template<class T>

struct MyQueue

{

void push(T &t)

{

s1.push(t);

}

T front()

{

if(s2.empty())

{

if(s1.size()== 0 ) throw;

while(!s1.empty())

{

s2.push(s1.top());

s1.pop();

}

}

return s2.top();

}

void pop()

{

if(s2.empty())

{

while(!s1.empty())

{

s2.push(s1.top());

s1.pop();

}

}

if(!s2.empty())

{

s2.pop();

}

}

stack<T> s1;

stack<T> s2;

};

void main()

{

MyQueue<int> mq;

int i;

for(i=0; i<10; i++)

mq.push(i);

for(i=0; i<10; i++)

{

cout<<mq.front()<<endl;

mq.pop();

}

system("pause");

}

程序来自<程序员面试宝典3>178页
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: