// stack.h
#ifndef _STACK_H_
#define _STACK_H_
#define MAX_STACK 10
typedef int T;
typedef struct
{
T *data;
int st;
} STACK;
STACK *createstack();
int push(STACK * s, T e);
T* pop(STACK *s);
void release(STACK *s);
void test_stack();
#endif
// stack.c
#include <stdio.h>
#include <stdlib.h>
STACK *createstack()
{
STACK *s;
s = (STACK *)malloc(sizeof(STACK));
if (!s) return 0;
s->data = (T*)malloc(MAX_STACK * sizeof(T));
if(!s->data)
{
free(s);
return 0;
}
s->st = 0;
return s;
}
int push(STACK * s, T e)
{
if (!s || !s->data) return 0;
if (s->st > MAX_STACK) return 0;
s->data[s->st++] = e;
return 1;
}
T* pop(STACK *s)
{
if (!s || !s->data) return 0;
if (s->st <= 0) return 0;
return &(s->data[--s->st]);
}
void release(STACK *s)
{
if (!s) return;
if (s->data)
while (s->st--)
free(&(s->data[s->st+1]));
free(s);
}
// 测试函数
void test_stack()
{
STACK *s = createstack();
T element;
for (int i=0; i<MAX_STACK; i++)
{
element = 1000+i;
push(s, element);
}
printf("pop element from stack: \n");
T *pElement = NULL;
for (int i=0; i<MAX_STACK; i++)
{
pElement = pop(s);
printf("%d ", *pElement);
}
release(s);
}
参考: