链表实现栈----《数据结构与算法设计》

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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37131037/article/details/80426529