栈:限定仅在表尾进行插入或删除操作的线性表,对栈来说,表尾端为栈顶,表头端为栈底。
本文实现了顺序栈的表示和相关函数操作,以及一些验证性代码。
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define TRUE 1
#define FALSE 0
#define ERROR 0
typedef int Status;
typedef int SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status Init_Stack(SqStack &S){
S.base=(SElemType*)malloc(sizeof(SElemType)*STACK_INIT_SIZE);
if(!S.base){
printf("Merry Error\n");
exit(0);
}
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
Status Clear_Stack(SqStack &S){
S.top=S.base;
return OK;
}
Status Stack_Empty(SqStack S){
if(S.top==S.base){
return TRUE;
}
else{
return FALSE;
}
}
int Stack_Length(SqStack S){
int length=0;
while(S.base!=S.top){
S.top--;
length++;
}
return length;
}
Status Get_Top(SqStack S,SElemType &e){
if(S.base==S.top){
return ERROR;
}
else{
e=*(S.top-1);
return OK;
}
}
Status Push(SqStack &S,SElemType e){
if(S.top-S.base>=S.stacksize){
S.base=(SElemType *)realloc(S.base,sizeof(SElemType)*(S.stacksize+STACKINCREMENT));
if(!S.base){
printf("Merroy Error!\n");
exit(0);
}
}
S.stacksize+=STACKINCREMENT;
*S.top++=e;
return OK;
}
Status Pop(SqStack &S,SElemType &e){
if(S.base==S.top){
return ERROR;
}
e=*(--S.top);
return OK;
}
Status Destroy_Stack(SqStack &S){
S.top=S.base;
free(S.base);
return OK;
}
int main(){
SqStack S;
int e;
int choice;
if(Init_Stack(S)){
printf("Init Stack OK!\n");
}
while(1){
printf("选择要进行的操作:\n");
printf("1、压栈 2、出栈\n");
printf("3、取栈顶 4、栈长度\n");
printf("5、清空栈 6、销毁栈\n");
scanf("%d",&choice);
switch(choice){
case 1:
printf("要压栈的数据:");
scanf("%d",&e);
Push(S,e);
break;
case 2:
if(Pop(S,e)){
printf("出栈的数据为:%d\n",e);
}
else{
printf("空栈,出栈失败!\n");
}
break;
case 3:
if(Get_Top(S,e)){
printf("栈顶元素为:%d\n",e);
}
else{
printf("空栈,出栈失败!\n");
}
break;
case 4:
printf("栈长度为:%d\n",Stack_Length(S));
break;
case 5:
Clear_Stack(S);
break;
case 6:
Destroy_Stack(S);
printf("栈已销毁!退出程序中\n");
Sleep(1000);
exit(0);
default:break;
}
}
return 0;
}
欢迎留言交流