堆栈
/*实现堆栈的初始化,入栈,出栈*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define STACK_INIT_SIZE 100
#define INCREMENT 10
typedef struct stack{
int * top;
int * base;
int stacksize;
}Stack;
int n;
void Init_Stack(Stack * S)/*堆栈初始化*/
{
S->base=(int *)malloc(STACK_INIT_SIZE * sizeof(int));
if(!S->base){printf("error!\n");exit(0);}
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
}
void Push_Stack(Stack * S,int e)/*堆栈入栈*/
{
if((S->top-S->base)>=S->stacksize)
{
S->base=(int *)realloc(S->base,(S->stacksize+INCREMENT)*sizeof(int));
if(!S->base)exit(0);
S->top=S->base+S->stacksize;
S->stacksize=S->stacksize+INCREMENT;
}
*S->top++=e;
n++;
}
void Pop_Stack(Stack * S,int * e)/*堆栈出栈*/
{
if(S->base==S->top)exit(0);
*e=*--S->top;
n--;
}
void Print_Stack(struct stack * S)/*显示堆栈数据*/
{
int i;
int * p1;
p1=S->base;
printf("\nNow stack have %d data:\n",n);
for(i=0;i<n;i++){
printf("%d ",*p1++);
}
printf("\n");
}
int main(int argc,char **argv)
{
struct stack S;
int k,j;
Init_Stack(&S);
Push_Stack(&S,12);
Push_Stack(&S,34);
Push_Stack(&S,56);
Print_Stack(&S);
Pop_Stack(&S,&k);
printf("\n%d data pop stack!\n",k);
Pop_Stack(&S,&j);
printf("%d data pop stack!\n",j);
Print_Stack(&S);
return 0;
}