C语言—数据结构系列---堆栈(一)

/*建立堆栈,执行入栈,出栈,打印输出操作*/

#include

#include

#define STACK_INIT_SIZE 100

#define STACK_INCREMENT 10

/*建立堆栈结构体*/

typedef struct {

int *top;

int *base;

int Init_Stack_size;

}SqStack;

/*初始化堆栈结构体*/

int Init_Stack(SqStack *s)

{

s->base = (int*)malloc(STACK_INIT_SIZE*sizeof(int));

s->top = s->base;

s->Init_Stack_size = STACK_INIT_SIZE;

return 0;

}

/*执行入栈操作*/

int push(SqStack *s,int e)

{

if(s->top-s->base>=s->Init_Stack_size)

{

s->base = (int*)realloc(s->base,(STACK_INIT_SIZE+STACK_INCREMENT)*sizeof(int));

s->top = s->base+s->Init_Stack_size;

s->Init_Stack_size +=STACK_INCREMENT;

}

*s->top++ = e; //栈顶指针指向下一个元素位置

return 0;

}

/*执行出栈操作,返回选中元素*/

int pop(SqStack *s)

{

int* e;

if(s->base == s->top) return 1;

e = malloc(sizeof(int)); //为出栈的元素建立空间

*e = *--s->top; //栈指针向下,选中栈顶出栈元素

return *e;

}

/*测试函数*/

int main()

{

int num;

SqStack s;

Init_Stack(&s); //初始化堆栈

push(&s,5);

num = pop(&s);

printf("The result is %d",num);

return 0;

}

你可能感兴趣的:(C语言—数据结构系列---堆栈(一))