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

面试题7—相关题目(两个队列实现栈)

2017-06-26 11:24 302 查看
代码示例:

#include<iostream>
#include<queue>
using namespace std;
//用两个队列模拟栈的操作
class CStack
{
public:
CStack()
{

}
~CStack()
{

}
void PushStack(int data);
bool PopStack(int &temp);
private:
queue<int>q1;
queue<int>q2;
};
void CStack::PushStack(int data)
{
if (q1.empty() && q2.empty())
{
q1.push(data);
return;
}
if (!q1.empty())
{
q1.push(data);
return;
}
if (!q2.empty())
{
q2.push(data);
return;
}
}
bool CStack::PopStack(int &temp)
{
if (!q1.empty())
{
while (!q1.empty())
{
temp = q1.front();
if (q1.size()!=1)
q2.push(temp);
q1.pop();
}
return true;
}
if (!q2.empty())
{
while (!q2.empty())
{
temp = q2.front();
if (q2.size()!=1)
q1.push(temp);
q2.pop();
}
return true;
}
return false;
}
void main()
{
CStack mystack;
int a[5] = { 5, 6, 8, 90, 1 };
for (int i = 0; i < 5; i++)
{
mystack.PushStack(a[i]);
}
int topvalue = 0;
for (int i = 0; i <5; i++)
{
bool flag = mystack.PopStack(topvalue);
if (flag)
{
cout << "出栈:" << topvalue << endl;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: