栈是一种重要的线性结构。从数据结构的角度讲,栈是线性表其特殊性在于栈的基本操作是线性表操作的子集,是操作受限的线性表。栈的特点是仅在表尾进行插入和删除操作的线性表,表尾是栈顶(top),表头是栈底,遵循后进先出的原则。因为栈是特殊的线性表,所以栈的实现也可以通过两种方式:顺序存储和链式存储。
这里主要讲栈的顺序存储实现,进行的操作主要包括:初始化、取栈顶、入栈、出栈、计算栈长度、销毁栈。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW 1
#define OK 0
#define ERROR -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)
exit(OVERFLOW);
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return OK;
}
Status GetTop(SqStack *S)
{
SElemType e;
if(S->top == S->base)
return ERROR;
e=*(S->top -1);
printf("栈顶元素是%d\n",e);
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)
exit(OVERFLOW);
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*S->top++ =e;
return OK;
}
Status Pop(SqStack *S)
{
if(S->top == S->base)
return ERROR;
SElemType e = *--S->top;
printf("%d",e);
return OK;
}
int StackLength(SqStack *S)
{
int i=0;
SElemType *p;
p=S->top;
if(p!=S->base)
{
p++;
i++;
}
return i;
}
Status DestroyStack(SqStack *S)
{
if(S->top!=S->base)
{
free(S->top);
S->top = S->base;
S->stacksize=0;
}
printf("Destroy Stack\n");
return OK;
}
int main()
{
SqStack *S;
int i;
S=(SqStack *)malloc(sizeof(SqStack));
InitStack(S);
for(i=0;i<5;i++)
Push(S,i);
GetTop(S);
printf("栈元素长度是:%d\n",StackLength(S));
printf("弹栈所有的元素是:");
while(S->top != S->base)
{
Pop(S);
}
printf("\n");
DestroyStack(S);
return 0;
}