C++顺序栈的基本操作
#include<iostream>
using namespace std;
#define MAXSIZE 10
typedef int Elemtype;
typedef struct
{
Elemtype elem[MAXSIZE];
int top;
}Seqstack;
void Initstack(Seqstack &s);
void Clear(Seqstack &s);
bool Isempty(Seqstack s);
bool Isfull(Seqstack s);
void Push(Seqstack &s, Elemtype e);
void Pop(Seqstack &s, Elemtype &e);
void Gettop(Seqstack s, Elemtype &e);
void Input(Seqstack &s);
void Output(Seqstack s);
void Interface();
int main()
{
Interface();
Seqstack s;
int n;
while (1)
{
cout << "请输入操作序号:";
cin >> n;
switch (n)
{
case 1:
{
Initstack(s);
break;
}
case 2:
{
Clear(s);
break;
}
case 3:
{
if (Isempty(s))
{
cout << "顺序栈为空!" << endl;
}
else
{
cout << "顺序栈不为空!" << endl;
}
break;
}
case 4:
{
if (Isfull(s))
{
cout << "顺序栈已满!" << endl;
}
else
{
cout << "顺序栈未满!" << endl;
}
break;
}
case 5:
{
Elemtype e;
cout << "请输入入栈元素:";
cin >> e;
Push(s, e);
break;
}
case 6:
{
Elemtype e;
Pop(s, e);
cout << "元素" << e << "已出栈!" << endl;
break;
}
case 7:
{
Elemtype e;
Gettop(s, e);
cout << "栈顶元素为:" << e << endl;
break;
}
case 8:
{
cout << "请依次输入数据,并以-1作为结束标记:" << endl;
Input(s);
break;
}
case 9:
{
cout << "顺序栈中的元素:" << endl;
Output(s);
break;
}
case 10:
{
Interface();
break;
}
case 0:
{
exit(0);
break;
}
default:
{
cout << "输入的操作序号不正确!请核对..." << endl;
}
}
}
return 0;
}
void Initstack(Seqstack &s)
{
s.top = -1;
}
void Clear(Seqstack &s)
{
s.top = -1;
}
bool Isempty(Seqstack s)
{
if (s.top == -1)
{
return true;
}
else
{
return false;
}
}
bool Isfull(Seqstack s)
{
if (s.top == MAXSIZE - 1)
{
return true;
}
else
{
return false;
}
}
void Push(Seqstack &s, Elemtype e)
{
if (Isfull(s))
{
cout << "顺序栈已满!" << endl;
}
else
{
s.top++;
s.elem[s.top] = e;
}
}
void Pop(Seqstack &s, Elemtype &e)
{
if (Isempty(s))
{
cout << "顺序栈为空!" << endl;
}
else
{
e = s.elem[s.top];
s.top--;
}
}
void Gettop(Seqstack s, Elemtype &e)
{
if (Isempty(s))
{
cout << "顺序栈为空!" << endl;
}
else
{
e = s.elem[s.top];
}
}
void Input(Seqstack &s)
{
int e;
while (1)
{
cin >> e;
if (e == -1)
{
break;
}
Push(s, e);
}
}
void Output(Seqstack s)
{
for (int i = s.top; i >= 0; i--)
{
cout << s.elem[i] << " ";
}
cout << endl;
}
void Interface()
{
cout << "***************欢迎使用顺序栈系统***************" << endl;
cout << "1:初始化顺序栈 2:清空顺序栈" << endl;
cout << "3:判断顺序栈是否为空 4:判断顺序栈是否已满" << endl;
cout << "5:入栈 6:出栈" << endl;
cout << "7:获取栈顶元素 8:输入顺序栈" << endl;
cout << "9:输出顺序栈 10:菜单" << endl;
cout << "0:退出" << endl;
cout << "*************************************************" << endl;
cout << "输入0-10之间的数:" << endl;
}