#include<stdio.h>
#include<malloc.h>
#include<process.h>
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
typedef struct SqStack{
int *base;
int *top;
int stacksize ;
}SqStack;
int InitStack(SqStack *S){
(*S).base = (int *)malloc(STACK_INIT_SIZE*sizeof(int));
if(!(*S).base)
exit(0);
(*S).top = (*S).base;
(*S).stacksize = STACK_INIT_SIZE;
return 1;
}
int Push(SqStack *S,int e){
if((*S).top-(*S).base>=(*S).stacksize){
(*S).base = (int *)realloc((*S).base,((*S).stacksize+STACKINCREMENT)*sizeof(int));
if(!(*S).base)
exit(0);
(*S).top = (*S).base +(*S).stacksize;
(*S).stacksize+=STACKINCREMENT;
}
*((*S).top) ++= e;
return 1;
}
int DestroyStack(SqStack *S){
free((*S).base);
(*S).base = NULL;
(*S).top = NULL;
(*S).stacksize = 0;
return 1;
}
int ClearStack(SqStack *S){
(*S).top = (*S).base;
return 1;
}
int StackEmpty(SqStack S){
if(S.top == S.base)
return 1;
else
return 0;
}
int StackLength(SqStack S){
return S.top-S.base;
}
int GetTop(SqStack S,int *e){
if(S.top>S.base){
*e = *(S.top-1);
return 1;
}
else
return 0;
}
int Pop(SqStack *S,int *e){
if((*S).top == (*S).base)
return 0;
*e = *--(*S).top;
return 1;
}
int StackTraverse(SqStack S,int(*visit)(int)){
while(S.top>S.base)
visit(*S.base++);
printf("\n");
return 1;
}
int visit(int c){
printf("%d ",c);
return 1;
}
void main(){
int j;
SqStack s;
int e;
if(InitStack(&s)==1)
for(j=1;j<12;j++)
Push(&s,j);
printf("the stack number order in ");
StackTraverse(s,visit);
//printf("%d ",(s.top));
Pop(&s,&e);
printf("stack empty? : %d(1:yes. 0 :no),%d\n",StackEmpty(s),e);
GetTop(s,&e);
printf("the pop number e = %d: the length:%d \n",e,StackLength(s));
ClearStack(&s);
printf("after clear ,empty?:%d\n",StackEmpty(s));
DestroyStack(&s);
printf("after destroy :s.top = %d ,s.base = %d,s.stacksize=%d\n",s.top,s.base,s.stacksize);
}
C语言栈代码
最新推荐文章于 2024-09-01 21:26:53 发布