首页 > 其他 > 详细

栈的链式存储实现

时间:2015-12-02 09:09:12      阅读:275      评论:0      收藏:0      [点我收藏+]
#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;
}SqStack;

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

    S->top = NULL;
}

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

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

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

    return NULL == S->top;
}

Status Push(SqStack *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(SqStack *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(SqStack *S, SElemType *e)
{
    assert(S);

    if (StackEmpty(S))
        return ERROR;

    *e = S->top->data;

    return OK;
}

void StackTraverse(SqStack *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()
{
    SqStack S;
    int c;

    InitStack(&S);

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

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

    DestroyStack(&S);

    putchar(\n);
    system("pause");
    return 0;
}

    运行结果:

技术分享

栈的链式存储实现

原文:http://www.cnblogs.com/inori/p/5011906.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!