主要功能:
?
?完整代码展示:
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct Stack{ //栈的存储结构
int *base; //栈底指针
int *top; //栈顶指针
int stacksize; //栈的最大容量
}SqStack;
bool InitStack(SqStack &S){ //初始化
S.base = new int[MAXSIZE];
if(!S.base){
cout<<"初始化失败"<<endl;
return false;
}
S.top = S.base;
S.stacksize = MAXSIZE;
cout<<"初始化成功"<<endl;
return true;
}
bool Push(SqStack &S, int e){ //入栈
if (S.top - S.base == S.stacksize) return false; //栈满
*S.top++ = e; //先赋值,再++; 相当于*S.top=e; S.top++;
return true;
}
void PushStack(SqStack &S){ //连续入栈
int n,e,flag;
cout<<"请输入入栈元素个数:";
cin>>n;
for (int i = 0; i < n; i++) {
printf("请输入第%d个元素值:",i+1);
cin>>e;
flag = Push(S,e);
if(flag) cout<<"入栈成功"<<endl;
else {
cout<<"栈已满"<<endl;
break;
}
}
}
bool Pop(SqStack &S, int &e){ //出栈
if(S.top == S.base) return false; //空栈
e = *--S.top; //先--,再赋值;相当于 --S.top; e=*S.top;
return true;
}
int GetTop(SqStack S, int &e){ //取栈顶元素
if(S.top != S.base)
e = *(S.top - 1);
return e;
}
void StackEmpty(SqStack S){ //判断是否为空
if(S.top == S.base) cout<<"栈为空"<<endl;
else cout<<"栈不为空"<<endl;
}
int StackLength(SqStack S){ //求栈的长度
return S.top - S.base;
}
bool ClearStack(SqStack &S){ //清空栈
if (S.base)
S.top = S.base;
return true;
}
bool DestoryStack(SqStack &S){ //销毁栈
if(S.base){
delete S.base;
S.stacksize = 0;
S.base = S.top = NULL;
}
return true;
}
int main() {
SqStack s;
int e;
cout<<"1.入栈------------2.连续入栈"<<endl;
cout<<"3.出栈------------4.取栈顶元素"<<endl;
cout<<"5.是否为空--------6.栈的长度"<<endl;
cout<<"7.清空栈----------8.销毁栈"<<endl;
cout<<"0.退出"<<endl;
int choice = -1;
InitStack(s);
while (choice !=0) {
cout << "请选择功能:";
cin >> choice;
switch (choice) {
case 1: //入栈
cout << "输入入栈元素值:";
cin >> e;
if (Push(s, e)) cout << "入栈成功" << endl;
else cout << "栈已满" << endl;
break;
case 2: //连续入栈
PushStack(s);
break;
case 3: //出栈
if (Pop(s, e)) cout << "出栈成功" << endl;
else cout << "栈为空" << endl;
break;
case 4: //取栈顶元素
cout << "栈顶元素为:" << GetTop(s, e)<< endl;
break;
case 5: //是否为空
StackEmpty(s);
break;
case 6: //栈长度
cout << "栈的长度为:" << StackLength(s)<< endl;
break;
case 7: //清空
if (ClearStack(s)) cout << "栈已清空" << endl;
break;
case 8: //销毁
if (DestoryStack(s)) cout << "栈已销毁" << endl;
break;
}
}
return 0;
}
?运行结果展示:
?
?
?
|