栈的链表实现(C语言版)

17 篇文章 0 订阅
12 篇文章 0 订阅

栈也是一种简单常用的数据结构,他的特点是先进先出。
现代化计算机将栈操作作为指令系统的一部分,栈也就有可能成为计算机科学中在数组之后最基本的数据结构。所以,栈的重要性就不用多说了。
其实现思路也比较简单,这里就不多解释了,直接看代码吧

#include "Stack.h"
#include <stdlib.h>

struct Node
{
    ElementType Element;
    PtrToNode Next;
};

void FatalError(char * s)
{

}

void Error(char * s)
{

}

int IsEmpty(Stack S)
{
    return S->Next == NULL;
}

Stack CreatStack(void)
{
    Stack S;

    S = malloc(sizeof(struct Node));
    if(S == NULL)
        FatalError("Out of space!!!");
    S->Next = NULL;
    MakeEmpty(S);
    return S;
}

void MakeEmpty(Stack S)
{
    if(S == NULL)
        Error("Must use CreateStack first");
    else
        while(!IsEmpty( S ))
            Pop(S);
}

void Push(ElementType X,Stack S)
{
    PtrToNode TmpCell;

    TmpCell = malloc(sizeof(struct Node));
    if(TmpCell == NULL)
        FatalError("Out of space!!!");
    else
    {
        TmpCell->Element = X;
        TmpCell->Next = S->Next;
        S->Next = TmpCell;
    }
}

ElementType Top(Stack S)
{
    if(!IsEmpty(S))
        return S->Next->Element;
    Error("Empty stack");
    return 0;
}

void Pop(Stack S)
{
    PtrToNode FirstCell;

    if(IsEmpty( S ))
        Error("Empty stack");
    else
    {
        FirstCell = S->Next;
        S->Next = S->Next->Next;
        free(FirstCell);
    }
}

void DisposeStack(Stack S)
{
    while(!IsEmpty(S))
        Pop(S);
}

int main()
{
    Stack S = CreatStack();
    Push(1,S);
    Push(2,S);
    Push(3,S);
    //DisposeStack(S);
    while(!IsEmpty(S))
    {
        printf("%d\n",Top(S));
        Pop(S);
    }
}

按照惯例,同样在后面加了个main函数用于测试,顺便把书上没有的几个实现也补上了

注:代码改编自《数据结构与算法分析》第二版

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值