您的位置:首页 > 职场人生

两个队列实现一个栈——栈和队列面试题(3)

2016-09-18 19:13 211 查看
题目要求:用两个队列实现一个栈,实现栈的内部函数



“test.cpp”

<strong><span style="font-size:18px;">#include<iostream>
using namespace std;
#include<queue>

template<class T>
class TwoQueueFromStack
{
public:
TwoQueueFromStack(){}

void Push(const T& data)
{
if(FirstQueue.empty())
{
ScondQueue.push(data);
}
else
{
FirstQueue.push(data);
}
}
void Pop()
{
if(FirstQueue.empty())
{
while(ScondQueue.size() != 1)
{
FirstQueue.push(ScondQueue.front());
ScondQueue.pop();
}
ScondQueue.pop();
}
else
{
while(FirstQueue.size() != 1)
{
ScondQueue.push(FirstQueue.front());
FirstQueue.pop();
}
FirstQueue.pop();
}
}
T& Top()
{
if(FirstQueue.empty())
{
return ScondQueue.back();
}
else
{
return FirstQueue.back();
}
}
size_t Size()
{
if(FirstQueue.empty())
{
return ScondQueue.size();
}
else
{
return FirstQueue.size();
}
}
bool Empty()
{
return FirstQueue.empty() && ScondQueue.empty();
}
private:
queue<T> FirstQueue;
queue<T> ScondQueue;
};

void test()
{
TwoQueueFromStack<int> s;
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
s.Push(5);
s.Push(6);
cout<<"top = "<<s.Top()<<endl;
cout<<"size = "<<s.Size()<<endl;
cout<<"empty = "<<s.Empty()<<endl;

s.Pop();
s.Pop();
s.Pop();
cout<<"top = "<<s.Top()<<endl;
cout<<"size = "<<s.Size()<<endl;
cout<<"empty = "<<s.Empty()<<endl;

s.Pop();
s.Pop();
s.Pop();
cout<<"empty = "<<s.Empty()<<endl;
}
int main()
{
test();
return 0;
}</span></strong>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: