C语言实现栈的创建、初始化、计数、插入、删除、输出栈顶元素、遍历等操作
代码仅适用于初学者
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define INFEASIBLE -1
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack *S)
{
S->base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(S->base==NULL) exit(OVERFLOW);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
return OK;
}
Status DestroyStack(SqStack *S)
{
free(S->base);
return OK;
}
Status StackEmpty(SqStack S)
{
if(S.top-S.base==0)
return TRUE;
else
return FALSE;
}
int StackLength(SqStack S)
{
return S.top-S.base;
}
Status GetTop(SqStack S,SElemType e)
{
if(S.top==S.base) return ERROR;
e=*(S.top-1);
return e;
}
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) exit(OVERFLOW);
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*S->top=e;
S->top++;
return OK;
}
Status Pop(SqStack *S,SElemType *e)
{
if(S->top==S->base) return ERROR;
*e=*--S->top;
return OK;
}
Status ClearStack(SqStack *S)
{
int i;
for(i=1;S->top-S->base>0;i++)
{
for(;S->top>S->base;)
--S->top;
}
return OK;
}
int visit(int i)
{
i = i+0 ;
return i;
}
Status StackTraverse(SqStack S)
{
SElemType *p;
for(p=S.base;p<S.top;p++)
{
*p=visit(*p);
printf("%d ",*p);
}
printf("\n");
return OK;
}
int main()
{
SqStack S;
int e=0,s=0;
int i,j=0;
InitStack(&S);
printf("初始往构建好的栈里面插入数据:1 2 3 4 5\n");
for(i=1;i<=5;i++)
Push(&S,i);
printf("现在的栈长度为:%d\n",StackLength(S));
printf("如果返回值为1,则为空栈,若为1,则为非空栈:%d\n",StackEmpty(S));
printf("现在的栈的顶元素为:%d\n", GetTop(S,e));
Pop(&S,&s);
printf("将这时候的栈的顶元素删除,返回删除的顶元素为:%d\n",s);
printf("下面对栈进行visit(访问每一个元素)遍历操作,返回的数据为:\n");
StackTraverse(S);
printf("若返回值为1,则成功将S置为空栈: %d\n",ClearStack(&S));
printf("若返回值为1,则成功将S销毁: %d\n",DestroyStack(&S));
system("pause");
return 0;
}