栈的链表实现(C语言)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunlanchang/article/details/81229451
// 栈的链表实现
#include <stdio.h>
#include <stdlib.h>

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
typedef int ElementType;

Stack CreateStack();
int IsEmpty(Stack S);
void Push(ElementType X, Stack S);
void Pop(Stack S);
void MakeEmpty(Stack S);
void PrintStack(Stack S);

struct Node
{
    ElementType Element;
    PtrToNode Next;
};

// 栈的初始化,申请空间
Stack CreateStack()
{
    Stack S;

    S = malloc(sizeof(struct Node));
    // 判断是否申请空间失败
    if (S == NULL)
    {
        printf("malloc memery failed!\n");
        return NULL;
    }

    S->Next = NULL;
    return S;
}

// 判断栈是否为空
int IsEmpty(Stack S)
{
    return S->Next == NULL;
}

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

    TmpCell = malloc(sizeof(struct Node));
    if (TmpCell == NULL)
    {
        printf("malloc memery failed!\n");
    }
    else
    {
        TmpCell->Element = X;
        TmpCell->Next = S->Next;
        S->Next = TmpCell;
    }
}

// 出栈
void Pop(Stack S)
{
    PtrToNode FirstCell = S->Next;
    if (IsEmpty(S))
    {
        printf("stack is empty!\n");
    }
    else
    {
        S->Next = FirstCell->Next;
        free(FirstCell);
    }
}

// 清空栈
void MakeEmpty(Stack S)
{
    if (S == NULL)
    {
        printf("make sure CreateStack first!\n");
    }
    else
    {
        while (!IsEmpty(S))
            Pop(S);
    }
}

// 打印栈的所有元素
void PrintStack(Stack S)
{
    PtrToNode TmpNode = S->Next;
    if (TmpNode == NULL)
        printf("stack is empty!\n");
    while (TmpNode != NULL)
    {
        printf("%d\n", TmpNode->Element);
        TmpNode = TmpNode->Next;
    }
}

int main()
{
    Stack S = CreateStack();
    for (int i = 1; i < 5; i++)
    {
        Push(i, S);
    }
    PrintStack(S);
    MakeEmpty(S);
    PrintStack(S);
    return 0;
}
阅读更多

没有更多推荐了,返回首页