stack.h
#ifndef STACK_H
#define STACK_H 1
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define STACK_MAX 256
struct snode
{
char name[32];
int num;
struct snode *next;
};
struct stack
{
int stacksize;
struct snode *top;
};
struct stack *initstack(struct stack **stackhead);
void destroystack(struct stack **stackhead);
void clearstack(struct stack *stackhead);
int stackempty(const struct stack *stackhead);
int stacklength(const struct stack *stackhead);
int push(struct stack *stackhead, struct snode *entry);
struct snode *pop(struct stack *stackhead);
void printsnode(const struct snode *node);
#endif /* STATC_H */
stack.c
#include <stack.h>
/*
struct snode
{
char name[32];
int num;
struct node *next;
};
struct stack
{
int stacksize;
struct node *top;
};
//*/
struct stack *initstack(struct stack **stackhead)
{
*stackhead = (struct stack *)malloc(sizeof(struct stack));
if(!*stackhead) {
return NULL;
}
(*stackhead)->stacksize = 0;
(*stackhead)->top = NULL;
return *stackhead;
}
void destroystack(struct stack **stackhead)
{
clearstack(*stackhead);
free(*stackhead);
*stackhead = NULL;
return;
}
void clearstack(struct stack *stackhead)
{
while(NULL != pop(stackhead));
return;
}
int stackempty(const struct stack *stackhead)
{
return 0 == stackhead->stacksize;
}
int stacklength(const struct stack *stackhead)
{
return stackhead->stacksize;
}
int push(struct stack *stackhead, struct snode *entry)
{
if(STACK_MAX == stackhead->stacksize) {
return -1;
}
entry->next = stackhead->top;
stackhead->top = entry;
++(stackhead->stacksize);
return 0;
}
struct snode *pop(struct stack *stackhead)
{
struct snode *entry = NULL;
if(stackhead->stacksize>0) {
--(stackhead->stacksize);
entry = stackhead->top;
stackhead->top = entry->next;
entry->next = NULL;
}
return entry;
}
void printsnode(const struct snode *node)
{
if(node) {
printf("name=%10s, num=%3d...\n", node->name, node->num);
} else {
printf("node is NULL...\n");
}
}