C++实现顺序栈相关操作代码

#include<iostream>
#include<cstdlib>
using namespace std;
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int Elemtype;
typedef struct
{
Elemtype* base;//栈底指针
Elemtype* top;//栈顶指针
int stacksize;//栈可用的最大容量
}Sqstack;
Status Initstack(Sqstack& s);//初始化顺序栈
Status Creatstack(Sqstack& s);//创建顺序栈
Status Insertstack(Sqstack& s, int x);//向顺序栈中插入元素
Status Popstack(Sqstack& s);//删除栈顶元素
Status Getstack(Sqstack s);//获取栈顶元素
Status Lenstack(Sqstack s);//顺序栈的长度
Status Printstack(Sqstack s);//输出顺序栈
int main(void)
{
Sqstack s;
int x;
int k;
do {
cout << "\n*****顺序栈相关操作*****";
cout << "\n1.初始化一个空栈";
cout << "\n2.随机创建一个包含正整数值的栈";
cout << "\n3.将一个数x插入到栈顶";
cout << "\n4.将栈顶元素弹出,并输出元素的值";
cout << "\n5.输出栈顶元素";
cout << "\n6.求栈的长度";
cout << "\n7.输出从栈顶到栈底的元素";
cout << "\n0.结束相关操作";
cout << "\n输入想要进行相关操作的序号:";
cin >> k;
switch (k)
{
case 1:
{
if (Initstack(s))
cout << "初始化成功。\n" << endl;
else
cout << "初始化失败。\n" << endl;
break;
}
case 2:
{
if (Creatstack(s))
{
cout << "创建成功。\n";
}
else
{
cout << "创建失败。\n";
}
break;
}
case 3:
{
cout << "输入想要插入元素的数值x为:";
cin >> x;
if (Insertstack(s, x)) cout << "插入成功。\n";
else cout << "插入失败。\n";
break;
}
case 4:
{
if (Popstack(s)) cout << "删除成功。\n";
else cout << "删除失败。\n";
break;
}
case 5:
{
if (Getstack(s)) cout << "输出成功。\n";
else cout << "输出失败。\n";
break;
}
case 6:
{
if (Lenstack(s)) cout << "长度获取成功。\n";
else cout << "长度获取失败。\n";
break;
}
case 7:
{
if (Printstack(s)) cout << "全部输出成功。\n";
else cout << "全部输出失败。\n";
break;
}
}
} while (k != 0);
return OK;
}
Status Initstack(Sqstack& s)
{
s.base = new Elemtype[MAXSIZE];//为顺序栈动态分配一个最大容量为MAXSIZE的数组空间
if (!s.base) exit(OVERFLOW);//存储分配失败
s.top = s.base;//top初始化为base,空栈
s.stacksize = MAXSIZE;//栈的最大容量为MXAXSIZE
return OK;
}
Status Creatstack(Sqstack& s)
{
int k = 0;
int len = 0;
cout << "\n栈包含的正整数len为:";
cin >> len;
cout << "\n输入正整数值为:";
for (int i = 0; i < len; i++)
{
cin >> k;
*(s.top) = k;
s.top++;//非空时,top始终是指向栈顶元素的上一个位置*s.top++
}
return OK;
}
Status Insertstack(Sqstack& s, int x)
{
if (s.top - s.base == s.stacksize) return ERROR;//判断栈是否满
*(s.top) = x;
s.top++;
cout << "插入元素为" << x << endl;
return OK;
}
Status Popstack(Sqstack& s)
{
if (s.base == s.top) return ERROR;//判断栈是否为空
s.top--;
int i = 0;
i = *(s.top);
cout << "删除元素为" << i << endl;
return OK;
}
Status Getstack(Sqstack s)
{
if (s.base == s.top) return ERROR;
int k = 0;
k = *(s.top - 1);
cout << "输出的栈顶元素为" << k << endl;
return OK;
}
Status Lenstack(Sqstack s)
{
int k = 0;
k = s.top - s.base;
cout << "栈的长度为" << k << endl;
return OK;
}
Status Printstack(Sqstack s)
{
if (s.base == s.top) return ERROR;//空栈
for (int k = 0; k < s.top - s.base; k++)
{
cout << *(s.top - k - 1) << " ";

}
cout << endl;
return OK;
}

posted @ 2023-01-09 19:06  师大无语  阅读(95)  评论(0编辑  收藏  举报