trix 发表于 2013-1-27 05:28:30

堆栈基本操作

#include <stdio.h>
#include <stdlib.h>
#define   STACK_INIT_SIZE   100
#define   INCREMENT_SIZE   10
typedef   char   ElemType;
typedef   struct   
{
ElemType   *base,*top;
int   stacksize;
}SqStack;

int   StackInit(SqStack   *);
int   Push(SqStack   *);
int   pop(SqStack   *);
int   GetTop(SqStack   *);

int   StackInit(SqStack   *S)
{
S-> base=(ElemType   *)malloc(STACK_INIT_SIZE   *   sizeof(ElemType));
if(!S-> base)   printf( "out   of   memory!\n ");
S-> top=S-> base;
S-> stacksize=STACK_INIT_SIZE;
return   1;
}

int   GetTop(SqStack   *S)
{
ElemType   e;
if(S-> top==S-> base)   return   0;
e=*(S-> top-1);
return   1;
}

int   Push(SqStack   *S)
{
if(S-> top-S-> base> =S-> stacksize)
{
S-> base=(ElemType   *)realloc(S-> base,(S-> stacksize+INCREMENT_SIZE)   *   sizeof(ElemType));
if(!S-> base)   exit(0);
S-> top=S-> base+S-> stacksize;         
S-> stacksize+=INCREMENT_SIZE;
}
printf( "请输入一个字符:\n ");
scanf( "%c ",S-> top++);   //此处有改动,应该把变量的地址传给scanf函数。
return   1;
}

int   Pop(SqStack   *S)
{
ElemType   e;
if(S-> top==S-> base)   return   0;
return   1;
e=*(--S-> top);
}


int   main()
{
SqStack   S;   //此处注意,指针必须让他指向东西才行。
StackInit(&S);
Push(&S);
GetTop(&S);
Pop(&S);
return   0;
}
页: [1]
查看完整版本: 堆栈基本操作