数据结构:(栈)C语言简单实现
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define ok 1
#define error -1
typedef int SElemType;
typedef int Status;
typedef struct SqStack
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack *S)
{
S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S->base){
printf("构造失败\n");
return error;
}
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
printf("构造成功\n");
return ok;
}
Status DestroyStack(SqStack *S)
{
S->top = NULL;
S->stacksize = 0;
free(S->base);
return ok;
}
Status ClearStack(SqStack *S)
{
S->top = S->base;
return ok;
}
Status StackEmpty(SqStack *S)
{
if(!S->base){
printf("未创建栈\n");
return error;
}
if(S->base == S->top)
printf("栈为空\n");
else{
printf("栈不为空\n");
}
return ok;
}
Status StackLength(SqStack *S)
{
return (S->top - S->base);
}
Status GetTop(SqStack *S, SElemType *e)
{
if(S->top == S->base)
return error;
*e = *(S->top);
return ok;
}
Status Push(SqStack *S,SElemType e)
{
if(S->top - S->base >= S->stacksize){
S->base = (SElemType *)realloc(S->base, (S->stacksize+STACKINCREMENT) * sizeof(SElemType));
if(!S->base)
return error;
S->top = S->base + S->stacksize;
S->stacksize = S->stacksize + STACKINCREMENT;
}
S->top++;
*S->top = e;
return ok;
}
Status Pop(SqStack *S, SElemType *e)
{
if(S->base == S->top)
return error;
*e = *S->top;
S->top--;
return ok;
}
Status StackTraverse(SqStack S, Status(* visit)(SElemType))
{
while(S.top > S.base){
S.base++;
visit(*S.base);
}
printf("\n");
return ok;
}
Status visit(SElemType e)
{
printf("%d ", e);
return ok;
}
int main()
{
int t;
SElemType e;
SqStack S;
while (1)
{
printf("================================\n");
printf(" 栈\n");
printf("================================\n");
printf("1:构造栈 2:进栈 3:出栈\n");
printf("4:销毁栈 5:清空栈 6:求栈长\n");
printf("7:判断栈是为空 8:返回栈顶元素 9:对栈调用visit()函数\n");
printf("--------------------------------\n");
printf("请选择:");
scanf("%d", &t);
switch (t)
{
case 1:
InitStack(&S);
break;
case 2:
printf("请输入要进栈的元素:");
scanf("%d",&e);
if(Push(&S,e) == 1)
{
printf("进栈成功\n");
}
break;
case 3:
if(Pop(&S,&e) == 1){
printf("取出的栈顶元素为:%d\n",e);
}else if(Pop(&S,&e) == -1){
printf("空栈没有元素\n");
}
break;
case 4:
if(DestroyStack(&S) == 1){
printf("销毁栈成功\n");
}
break;
case 5:
if(ClearStack(&S) == 1){
printf("清空栈成功\n");
}
break;
case 6:
printf("栈长为:%d\n",StackLength(&S));
break;
case 7:
StackEmpty(&S);
break;
case 8:
if(GetTop(&S,&e) == 1){
printf("栈顶元素为:%d\n",e);
}
break;
case 9:
StackTraverse(S,visit);
break;
}
}
return 0;
}
|