栈的链式存储实现

#define ERROR           0
#define OK              1
#define OVERFLOW       -1

typedef int Status;
typedef int SElemType;
typedef struct SNode
{
    SElemType data;
    struct SNode *next;
}SNode;
typedef struct
{
    SNode *top;
}LinkStack;

void InitStack(LinkStack *S)
{
    assert(S);

    S->top = NULL;
}

void DestroyStack(LinkStack *S)
{
    assert(S);
    SNode *tmp = S->top;

    while (tmp)
    {
        S->top = tmp->next;
        free(tmp);
        tmp = S->top;
    }
}

Status StackEmpty(LinkStack *S)
{
    assert(S);

    return NULL == S->top;
}

Status Push(LinkStack *S, SElemType e)
{
    assert(S);
    SNode *tmp;

    tmp = (SNode *)malloc(sizeof(SNode));
    if (!tmp)
        exit(OVERFLOW);

    tmp->data = e;
    tmp->next = S->top;
    S->top = tmp;

    return OK;
}

Status Pop(LinkStack *S, SElemType *e)
{
    assert(S);
    SNode *tmp;

    if (StackEmpty(S))
        return ERROR;

    tmp = S->top;
    S->top = tmp->next;
    if (e)
        *e = tmp->data;
    free(tmp);

    return OK;
}

Status GetTop(LinkStack *S, SElemType *e)
{
    assert(S);

    if (StackEmpty(S))
        return ERROR;

    *e = S->top->data;

    return OK;
}

void StackTraverse(LinkStack *S, void(*visit)(SElemType *))
{
    assert(S&&visit);
    SNode *tmp;

    tmp = S->top;
    while (tmp)
    {
        visit(&tmp->data);
        tmp = tmp->next;
    }
}

    测试程序:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

void visit(SElemType *e)
{
    putchar(*e);
}

int main()
{
    LinkStack S;
    int c;

    InitStack(&S);

    while ('
' != (c = getchar()))
        Push(&S, c);

    StackTraverse(&S, visit);
    putchar('
');
    while (!StackEmpty(&S))
    {
        Pop(&S, &c);
        visit(&c);
    }

    DestroyStack(&S);

    putchar('
');
    system("pause");
    return 0;
}

    运行结果:

栈的链式存储实现

    栈的顺序存储实现请戳这里