- typedef int SElemType;
- typedef int Status;
- typedef struct{
- SElemType *top,*base;//定义栈顶和栈底指针
- int stacksize;//定义栈的容量
- }SqStack;
- Status InitStack(SqStack &S){//初始化一个空栈
- S.base=new SElemType[MAXSIZE];//为顺序栈动态分配一个最大容量为MAXSIZE的空间
- if(S.base==NULL) return ERROR;//判断存储是否分配成功
- S.top=S.base;//将top初始化为base,置为空栈
- S.stacksize=MAXSIZE;//stacksize置为最大容量MAXSIZE
- return OK;
- }
- Status Push(SqStack &S,SElemType e){//入栈
- if(S.top-S.base==S.stacksize) return ERROR;//判断是否栈满
- *S.top=e;
- S.top++;
- return OK;
- }
- Status Pop(SqStack &S,SElemType &e){//出栈
- if(S.top==S.base) return ERROR;//判断栈是否为空
- S.top--;
- e=*S.top;
- return OK;
- }
- Status PrintfStack(SqStack S){//遍历栈内的所有元素
- SElemType *p;
- p=S.base;
- printf("栈中的元素为:");
- while(p!=S.top){
- printf("%d ",*p);
- p++;
- }
- printf("\n");
- }
- SElemType GetTop(SqStack S){//获取栈顶元素
- if(S.top!=S.base)//当栈不为空时
- return *(S.top-1);
- }
- int StackLength(SqStack S){//获取栈的长度
- int len=0;
- SElemType *s;
- s=S.base;//从栈底开始
- while(s!=S.top){
- len++;
- s++;
- }
- printf("栈的长度为:%d\n",len);
- }
- Status StackEmpty(SqStack S){//判断栈是否为空
- if(S.top==S.base) return ERROR;
- else
- return OK;
- }
- #include
- #define MAXSIZE 100
- #define ERROR 0
- #define OK 1
- typedef int SElemType;
- typedef int Status;
- typedef struct{
- SElemType *top,*base;//定义栈顶和栈底指针
- int stacksize;//定义栈的容量
- }SqStack;
- Status InitStack(SqStack &S){//初始化一个空栈
- S.base=new SElemType[MAXSIZE];//为顺序栈动态分配一个最大容量为MAXSIZE的空间
- if(S.base==NULL) return ERROR;//判断存储是否分配成功
- S.top=S.base;//将top初始化为base,置为空栈
- S.stacksize=MAXSIZE;//stacksize置为最大容量MAXSIZE
- return OK;
- }
- Status Push(SqStack &S,SElemType e){//入栈
- if(S.top-S.base==S.stacksize) return ERROR;//判断是否栈满
- *S.top=e;
- S.top++;
- return OK;
- }
- Status Pop(SqStack &S,SElemType &e){//出栈
- if(S.top==S.base) return ERROR;//判断栈是否为空
- S.top--;
- e=*S.top;
- return OK;
- }
- Status PrintfStack(SqStack S){//遍历栈内的所有元素
- SElemType *p;
- p=S.base;
- printf("栈中的元素为:");
- while(p!=S.top){
- printf("%d ",*p);
- p++;
- }
- printf("\n");
- }
- SElemType GetTop(SqStack S){//获取栈顶元素
- if(S.top!=S.base)
- return *(S.top-1);
- }
- int StackLength(SqStack S){//获取栈的长度
- int len=0;
- SElemType *s;
- s=S.base;
- while(s!=S.top){
- len++;
- s++;
- }
- printf("栈的长度为:%d\n",len);
- }
- Status StackEmpty(SqStack S){//判断栈是否为空
- if(S.top==S.base) return ERROR;
- else
- return OK;
- }
- int main()
- {
- SqStack S;
- InitStack(S);
- int n;
- printf("请输入要入栈的元素个数:");
- scanf("%d",&n);
- printf("请输入要入栈的元素:");
- for(int i=0;i
//将待入栈的元素依次存入栈中 - SElemType e;
- scanf("%d",&e);
- Push(S,e);
- }
- if(StackEmpty(S))
- printf("栈不为空!\n");
- else
- printf("栈为空!\n");
- int x=GetTop(S);
- printf("栈顶元素为:%d\n",x);
- StackLength(S);
- PrintfStack(S);
- printf("元素出栈:");
-