C++中能方便的建立栈(stack)和队列(queue);
但如何用两个站模拟队列呢;
(不足:只能存正整数,因为定义了正整数栈;)
下面是其中一种思路;
//This code was write by Hupeng
//This code could run in VS 2013
#include <iostream>
#include <stack>
#include <conio.h>
using namespace std;
class queue
{
public:
void push(int n)
{
STD_stack.push(n);
}
int pop()
{
int n;
while (!STD_stack.empty())
{
STD_temp.push(STD_stack.top());
STD_stack.pop();
}
n = STD_temp.top();
STD_temp.pop();
while (!STD_temp.empty())
{
STD_stack.push(STD_temp.top());
STD_temp.pop();
}
return n;
}
int front()
{
int n;
while (!STD_stack.empty())
{
STD_temp.push(STD_stack.top());
STD_stack.pop();
}
n = STD_temp.top();
while (!STD_temp.empty())
{
STD_stack.push(STD_temp.top());
STD_temp.pop();
}
return n;
}
int empty()
{
if (STD_stack.empty())
return 1;
return 0;
}
protected:
private:
stack<int>STD_stack;
stack<int>STD_temp;
};
int main()
{
char c;
int n;
int flag = 0;
queue example;
cout << "这是一个整型队列(尽量储存正整数):" << endl;
while (true)
{
cout << "请选择所要进行的操作:" << endl;
cout << "1. push" << endl << "2. pop" << endl << "3. front" << endl << "4. empty" << endl << "0. exit" << endl;
c = _getch();
switch (c)
{
case '0': flag = 1; break;
case '1':
{
cout << "请输入一个正数:" << endl;
cin >> n;
example.push(n);
}break;
case '2':
{
if (example.empty())
{
cout << "队列为空!" << endl;
}
else
{
cout << "弹出:" << example.pop() << endl;
}
} break;
case '3':
{
if (example.empty())
{
cout << "队列为空!" << endl;
}
else
{
cout << "队首元素:" << example.front() << endl;
}
}break;
case '4':
{
if (example.empty())
{
cout << "队列为空!" << endl;
}
else
{
cout << "队列不为空!" << endl;
}
}
default:
break;
}
if (flag)
{
break;
}
}
return 0;
}