//stack basic operation
//sequent list
//if base=top null stack
#include<stdio.h>
#include<iostream.h>
#include<malloc.h>//free
#include<cstdlib>
#include<math.h>
#include<string>
#define MAXSIZE 100
#define OK 1
#define ERROR 0//宏
typedef int Status;
typedef struct
{
char opera[30];
int data;
}ElemType;
typedef struct
{
ElemType *base;//栈底
ElemType *top;//栈顶
int stacksize;//栈可用最大容量
}SqStack;
//存储结构over
Status InitStack(SqStack &S)
{
S.base=(ElemType *)malloc(MAXSIZE*sizeof(ElemType));
if(!S.base) exit(OVERFLOW);
S.top=S.base;//初始top指向base
S.stacksize=MAXSIZE;
return OK;
}//初始化
Status Push(SqStack &S,ElemType &e)
{//一串连续的地址可以相加减ですか
if(S.top-S.base==S.stacksize) return ERROR;
*S.top++=e;//ご注意
return OK;
}
Status Pop(SqStack &S,ElemType &e)
{
if(S.top==S.base) return ERROR;
e=*--S.top;//ご注意
return OK;
}
ElemType GetTop(SqStack S)
{//返回栈顶元素,不修改栈顶指针
if(S.base!=S.top) return *(S.top-1);//非空
}
Status EnterData(SqStack &S)
{//for test
cout<<"かずくれね?"<<endl;
int length=0;
cin>>length;
cout<<"number,opera"<<endl;
for(int i=0;i<length;i++)
{
ElemType e;
cin>>e.data>>e.opera;
Push(S,e);
}
return OK;
}
void StackTraverse(SqStack S)
{//use GetTop()
ElemType e;
int length=0;
while(S.base!=S.top)
{
e=GetTop(S);
cout<<e.data<<e.opera<<endl;
--S.top;
length++;
}
cout<<"总计"<<length<<endl;
}
Status DestroyStack(SqStack &S)
{
free(S.base);//释放malloc(或calloc、realloc)函数给指针变量分配的内存空间的函数
S.base = NULL;//使用后该指针变量一定要重新指向NULL,防止野指针出现,规避误操作。
S.top = NULL;
S.stacksize = 0;
return OK;
}
void main()
{
SqStack S;
InitStack(S);
EnterData(S);
cout<<"希望成功录入数据..."<<endl;
StackTraverse(S);
cout<<"执行销毁"<<DestroyStack(S)<<endl;
system("pause");
}
顺序栈表示与实现
最新推荐文章于 2023-06-01 14:49:37 发布