C语言栈的单链表实现(源码笔记)

stackli.h

typedef int ElementType;
/* START: fig3_39.txt */
#ifndef _Stack_h
#define _Stack_h

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;

int IsEmpty(Stack S);

Stack CreateStack(void);

void DisposeStack(Stack S);

void MakeEmpty(Stack S);

void Push(ElementType X, Stack S);

ElementType Top(Stack S);

void Pop(Stack S);

#endif  /* _Stack_h */

/* END */

stackli.c

#include "stackli.h"
#include "fatal.h"
#include <stdlib.h>

// 节点
struct Node
{
    ElementType Element;
    PtrToNode Next;
};

/* START: fig3_40.txt */
// 判断栈是否为空,判断方法为判断头节点S指向的下一个节点是否为空
int
IsEmpty(Stack S)
{
    return S->Next == NULL;
}
/* END */

/* START: fig3_41.txt */
// 创建一个栈,主要是创建一个头节点
Stack
CreateStack(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);
}

/* END */

// 处理掉这个栈,即清空所有元素并释放头节点
void
DisposeStack(Stack S)
{
    MakeEmpty(S);
    free(S);
}

/* START: fig3_42.txt */
// 进栈操作
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;
    }
}
/* END */

/* START: fig3_43.txt */
// 返回栈顶元素
ElementType
Top(Stack S)
{
    if (!IsEmpty(S))
        return S->Next->Element;
    Error("Empty stack");
    return 0;  /* Return value used to avoid warning */
}
/* END */

/* START: fig3_44.txt */
// 弹出栈顶元素
void
Pop(Stack S)
{
    PtrToNode FirstCell; // 第一个单元,即栈顶

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

teststkl.c(main.c)

#include <stdio.h>
#include "stackli.h"

int main()
{
    Stack S;
    int i;

    S = CreateStack();
    // 添加元素 0 ~ 9
    for (i = 0; i < 10; i++)
        Push(i, S);

    while (!IsEmpty(S))
    {
        printf("%d
", Top(S));
        Pop(S);
    }

    DisposeStack(S);
    return 0;
}

fatal.h

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

#define Error( Str )        FatalError( Str )
#define FatalError( Str )   fprintf( stderr, "%s
", Str ), exit( 1 )

运行结果:

原文地址:https://www.cnblogs.com/fanlumaster/p/13698128.html