【数据结构】顺序栈的基本操作

来源:互联网 发布:python 游戏开发框架 编辑:程序博客网 时间:2024/04/29 22:36



#include<iostream>using namespace std;typedef int SElemType;typedef struct{ SElemType *base; SElemType *top; int stacksize;}SqStack;void CreatSqStack(SqStack &S,int n){ S.base = new int; S.stacksize = n + 5; cout << "请输入栈元素:" << endl; for (int i = 0; i < n; i++)  cin >> S.base[i]; S.top = S.base + n;}int GetMax(SqStack S){ if (S.top == S.base) {  cout << "空栈!" << endl;  return 0; } SElemType max = S.base[0]; for (int i = 1; i < S.top - S.base; i++)  if (max < S.base[i])   max = S.base[i]; return max;}SElemType GetTop(SqStack S){ if (S.top == S.base) {  cout << "空栈!" << endl;  return 0; } int e = *(S.top - 1); return e;}void PushElem(SqStack &S, SElemType e){ S.stacksize = S.stacksize + 1; *S.top = e; *S.top++;}SElemType PopElem(SqStack &S){ if (S.top == S.base) {  cout << "空栈!" << endl;  return 0; } SElemType e = *(S.top - 1); *S.top--; return e;}void PrintSqStack(SqStack S){ cout << "现在栈里面的元素为:" << endl; for (int k = 0; k < S.top - S.base; k++)  cout << S.base[k]<< " "; cout << endl;}int main(){ SqStack S; int n; cout << "请输入栈里面的元素个数n:" << endl; cin >> n; CreatSqStack(S, n); PrintSqStack(S); cout << "栈里面元素的最大值为:" << endl << GetMax(S) << endl; cout << "栈顶的元素为:" << endl << GetTop(S) << endl; int e; cout << "请输入要进栈的元素e:" << endl; cin >> e; PushElem(S, e); PrintSqStack(S); cout << "出栈元素为:" << endl << PopElem(S) << endl; return 0;} 


10 0