list_stack.h
#define STACK_TYPE char
void destroy_stack();
void push(STACK_TYPE a);
void pop();
STACK_TYPE top();
int is_empty();
list_stack.c
#include "list_stack.h"
#include <stdlib.h>
#include <assert.h>
#include <malloc.h>
typedef struct node
{
STACK_TYPE data;
struct node *pnext;
}N_TYPE;
static N_TYPE *ptop = NULL;
void destroy_stack()
{
N_TYPE *ptemp;
if(!is_empty())
{
if(ptop->pnext == NULL)
{
free(ptop);
}
else
{
ptemp = ptop->pnext;
for(;ptemp->pnext != NULL; ptemp = ptop->pnext)
{
free(ptop);
ptop = ptemp;
}
free(ptemp);
ptemp = NULL;
}
ptop = NULL;
}
}
void push(STACK_TYPE a)
{
N_TYPE *ptemp;
if(is_empty())
{
if((ptop = (N_TYPE *)malloc(sizeof(N_TYPE))) == NULL)
{
perror("malloc: ");
exit(1);
}
ptop->pnext = NULL;
}
else
{
ptemp = (N_TYPE *)malloc(sizeof(N_TYPE));
if(ptemp == NULL)
{
perror("malloc: ");
exit(1);
}
ptemp->pnext = ptop;
ptop = ptemp;
}
ptop->data = a;
}
void pop()
{
N_TYPE *ptemp;
assert(!is_empty());
if(ptop->pnext == NULL)
{
free(ptop);
ptop = NULL;
}
else
{
ptemp = ptop;
ptop = ptop->pnext;
free(ptemp);
ptemp = NULL;
}
}
STACK_TYPE top()
{
assert(!is_empty());
return ptop->data;
}
int is_empty()
{
return ptop == NULL;
}
test.c
#include "list_stack.h"
#include <stdio.h>
void main()
{
push('a');
push('b');
push('c');
push('d');
push('e');
pop();
pop();
printf("top = %c/n", top());
destroy_stack();
push('a');
push('d');
push('3');
pop();
printf("top = %c/n", top());
}