文档介绍:C语言数据结构之栈的基本操作
程序结构图
main
GetTop
StackEmpty
Nizhi
Pop
Push
StackLength
InitStack
算法及其功能函数
InitStack(SqStack *S) /*创建栈*/
GetTop(SqStack *S,SElemType e) /*取栈顶元素并用e返回*/
Push(SqStack *S,SElemType e) /*插入e为栈顶元素*/
Pop(SqStack *S,SElemType *e) /*删除栈顶元素并用e返回*/
StackEmpty(SqStack S) /*判断栈是否为空*/
StackLength(SqStack S) /*求栈的长度*/
Nizhi(SqStack S) /*将栈中元素逆置*/
源代码
#include <>
#include <>
#define OK 1
#define OVERFLOW -2
typedef int Status;
typedef int SElemType;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack *S)
{
int i,n;
SElemType e;
S->base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S->base)
exit (OVERFLOW);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
printf("请输入栈内的数据个数:");
scanf("%d",&n);
if(n>=S->stacksize)
{
S->base=(SElemType *)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S->base) exit(OVERFLOW); }
for(i=0;i<n;i++)
{
printf("输入元素:");
scanf("%d",&e);
*(S->top)=e;
S->top=S->top+1;
}
return OK;}
Status Init(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 0;
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;}
printf("请输入要插入的栈顶元素:");
scanf("%d",&e);
*S->top++=e;
return OK;
}
void PushSq(SqStac