1.stack.h
#ifndef _STACK_H
#define _STACK_H
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#include "tree.h"
#define INIT_SIZE 10
#define INCREMENT 10
//#include "data.h"
typedef TREE * ElementType ;
typedef struct
{
ElementType* top,*bottom;
int size;
}STACK;
STACK* initSTACK();
void push(STACK* stack ,ElementType* p);
void destroy(STACK* stack );
int pop(STACK* stack,ElementType* p);
bool isEmpty(STACK* stack);
#endif;
2.stack.c
//typedef int ElementType;
#include "stack.h"
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
STACK* initSTACK(){
STACK* stack=(STACK*)malloc(sizeof(STACK));
stack->bottom=(ElementType*)malloc(INIT_SIZE*sizeof(STACK));
stack->top=stack->bottom;
stack->size=INIT_SIZE;
printf("bottom=%d\n",stack->top);
return stack;
}
void push(STACK* stack, ElementType* p)
{
if(stack->top-stack->bottom==stack->size)
{
stack->bottom=(ElementType*)realloc(stack->bottom,(stack->size+INCREMENT)*sizeof(STACK));
stack->top=stack->bottom+stack->size;
stack->size=stack->size+INCREMENT;
printf("realloc bottom=%d\n",stack->bottom);
}
*stack->top=*p;
stack->top++;
printf("top=%d\n",stack->top);
}
int pop(STACK* stack,ElementType* p)
{
if(stack==NULL||p==NULL)
return 0;
if(stack->bottom==stack->top)
return 0;
stack->top--;
*p=*stack->top;
return 1;
}
void destroy(STACK* stack )
{
free(stack->bottom);//好像有问题
free(stack);
}
bool isEmpty(STACK* stack){
if(stack->top==stack->bottom)
return true;
return false;
}
3.main.c
//typedef int ElementType;
//#define ElementType TREE ;
#include "tree.h"
#include "stack.h"
int main()
{
int a;
STACK* sta=initSTACK();
a=2;
push(sta,&a);
a=3;
push(sta,&a);
a=4;
push(sta,&a);
while(!isEmpty(sta))
{pop(sta,&a);
printf("%d\n",a);
}
return 0;
}