linkStack.h
个人笔记
#include <malloc.h>
#define Error(module) fprintf(stderr,"error:"#module"\n")
typedef int StackItem;
typedef struct stacknode *slink;
typedef struct stacknode {
StackItem element;
slink next;
}StackNode;
slink NewStackNode(){
slink p;
if( (p=malloc(sizeof(StackNode)))==0 )
Error("Exhausted memory.");
return p;
}
typedef struct lstack *Stack;
typedef struct lstack{
slink top;
}Lstack;
Stack StackInit() {
Stack S = malloc(sizeof(*S));
S->top = 0;
return S;
}
int StackIsEmpty(Stack S) {
return S->top == 0;
}
int StackFull(Stack S) {
return StackMemFull();
}
int StackMemFull(){
slink q;
if( (q=malloc(sizeof(StackNode))) == 0 )
return 1;
else {
free(q);
return 0;
}
}
StackItem StackTop(Stack S) {
if( StackIsEmpty(S) ) {
Error("Stack is empty.");
} else {
return S->top->element;
}
}
StackItem StackPop(Stack S) {
slink p;
StackItem x;
if( StackIsEmpty(S) ) {
Error("Stack is Empty.");
} else {
x = S->top->element;
p = S->top;
S->top = p->next;
free(p);
return x;
}
}
void StackPush(StackItem x, Stack S) {
slink p;
if( StackFull(S) ) {
Error("Stack is full.");
} else {
p = NewStackNode();
p->element = x;
p->next = S->top;
S->top = p;
}
}