- 用顺序存储结构表示的栈,称为顺序栈,它用一个顺序表和栈顶指针实现。
- 顺序表中,用top指针指示栈顶元素在顺序栈中的位置.
- 当top指针与base指针指向相同位置时栈为空.
#include <iostream>
#define MaxSize 30
using namespace std;
typedef struct Stack
{
int* base;
int* top;
int stacksize;
}SqStack;
int InitStack(SqStack& s)
{
s.base = new int[100];
if (!s.base)
{
cout << "分配失败" << endl;
return 0;
}
s.top = s.base;
s.stacksize = MaxSize;
return 1;
}
void menu()
{
cout << "--------------------1.入栈 2.出栈--------------------" << endl;
cout << "--------------------3.删除栈顶 4.遍历栈--------------------" << endl;
cout << "--------------------5.求栈长度 6.清空栈--------------------" << endl;
cout << "--------------------7.销毁栈 8.退出--------------------" << endl;
}
void PushToStack(SqStack &s)
{
int n, e, flag;
cout << "请输入需要入栈的元素个数:" << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "请输入元素的值:" << endl;
cin >> e;
if (s.top - s.base == MaxSize)
{
cout << "栈满,出栈" << endl;
return;
}
*(s.top++) = e;
}
}
void PopFromStack(SqStack& s)
{
int n, flag, e;
cout << "请输入需要出栈的元素个数:" << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
if (s.top == s.base)
{
cout << "栈已空" << endl;
return;
}
e = *(--s.top);
cout << e << "已出栈" << endl;
}
}
void GetTopOfStack(SqStack s)
{
if (s.top == s.base)
{
cout << "栈为空" << endl;
return;
}
int e = *(--s.top);
cout << "栈顶元素为:" << e << endl;
}
void TraveStack(SqStack s)
{
while (s.base != s.top)
cout << *(--s.top) << " ";
if (s.base == s.top)
{
cout << "栈已完成遍历" << endl;
return;
}
}
void LengthStack(SqStack& s)
{
if (s.base == s.top)
{
cout << "栈为空" << endl;
return;
}
cout << s.top - s.base << endl;
}
void ClearStack(SqStack& s)
{
s.top = s.base;
return;
}
void DestroyStack(SqStack& s)
{
s.top = nullptr;
s.stacksize = 0;
delete(s.base);
return;
}
int main()
{
SqStack s;
int choice;
InitStack(s);
while (1)
{
menu();
cout << "请输入菜单序号:" << endl;
cin >> choice;
if (choice == 8)
break;
switch (choice)
{
case 1:
PushToStack(s); break;
case 2:
PopFromStack(s); break;
case 3:
GetTopOfStack(s); break;
case 4:
TraveStack(s); break;
case 5:
LengthStack(s); break;
case 6:
ClearStack(s); break;
case 7:
DestroyStack(s); break;
default:
cout << "输入错误,请重新输入" << endl;
break;
}
}
return 0;
}