栈只是一种具有特殊规则的线性表,它的操作原理和线性表几乎相同。
#include<stdio.h>
#include<malloc.h>
#define INIT_SIZE 1
#define INCREASE 10
typedef int ElemType;
typedef struct
{
ElemType *top;
ElemType *base;
int length;
int size;
/* data */
}Stack;
void init_stack(Stack *p){
p->base = p->top = (ElemType *)malloc(INIT_SIZE*sizeof(ElemType));
p->length = 0;
p->size = INIT_SIZE;
}
void show(Stack *p){
if(p->top == p->base){
printf("THE STACK IS NULL");
return ;
}
//要把top指针的指向传给一个中间点,通过该点实现遍历
ElemType *q = p->top-1;
while(q >= p->base){
printf("%2d",*q);
q--;
}
printf("\n");
}
void push(Stack *p, ElemType e){
if(p->length >= p->size){
p->base = (ElemType *)realloc(p->base,(p->size+INCREASE)*sizeof(ElemType));
p->top = p-> base + p->length;
p->size += INCREASE;
}
*p->top++ = e;
p->length++;
}
void pop(Stack *p, ElemType *e){
if(p->top == p->base){
printf("THE STACK IS NULL");
return ;
}
*e = *--p->top;
p->length--;
}
int main(){
ElemType m;
Stack stack;
init_stack(&stack);
push(&stack,2);
push(&stack,4);
show(&stack);
pop(&stack,&m);
show(&stack);
printf("%d\n",m);
return 0;
}