栈———链表实现

Posted crel-devi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了栈———链表实现相关的知识,希望对你有一定的参考价值。

栈的链表实现细节主要在Push()和Pop()例程中链表的实现不一样。

Stack.c:

#ifndef STACK_H
#define STACK_H

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

int IsEmpty(Stack S);
Stack CreatStack();
void MakeEmpty(Stack S);
void DiseposeStack(Stack S);
void Push(Stack S, ElementType X);
void Pop(Stack S);
ElementType Top(Stack S);
ElementType PopAndTop(Stack S);

#endif

LinkedStack.c:

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

struct Node{
    ElementType Element;
    PtrToNode Next;
};

Stack CreatStack()
{
    Stack S;
    S = (Stack)malloc(sizeof(struct Node));
    if(S == NULL)
    {
        printf("sorry! malloc is failed!");
        return NULL;
    }
    else
    {
        S->Next = NULL;
        MakeEmpty(S);//confirm the stack is emptystack
    }
    return S;
}

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

void MakeEmpty(Stack S)
{
    if(S == NULL)
        printf("Please creatstack first!");
    while(!IsEmpty(S))
        Pop(S);
}

void DiseposeStack(Stack S)
{
    PtrToNode P, Tmp;
    P = S->Next;
    S->Next = NULL;
    while(P != NULL)
    {
        Tmp = P->Next;
        free(P);
        P = Tmp;
    }
}

void Push(Stack S, ElementType x)
{
    PtrToNode TmpCell;
    
    TmpCell = (Stack)malloc(sizeof(struct Node));
    if(TmpCell == NULL)
        printf("Sorry! malloc is failed!");
    else
    {
        TmpCell->Element = x;
        TmpCell->Next = S->Next;
        S->Next = TmpCell;
    } 
}

void Pop(Stack S)
{
    PtrToNode FirstCell;
    
    if(IsEmpty(S))
        printf("Sorry the stack is empty!");
    else
    {
        FirstCell = S->Next;
        S->Next = FirstCell->Next;
        //S->Next = S->Next->Next;//这样最安全
        free(FirstCell);
    }
}

ElementType Top(Stack S)
{
    if(!IsEmpty(S))
        return S->Next->Element;
    printf("Sorry! the stack is empty");
    return 0;
}

ElementType PopAndTop(Stack S)
{
    PtrToNode FirstCell;
    ElementType FirstElement;
    
    if(IsEmpty(S))
        printf("Sorry the stack is empty!");
    else
    {
        FirstCell = S->Next;
        FirstElement = S->Next->Element;
        S->Next = S->Next->Next;
        free(FirstCell);
        return FirstElement;
    }
}

 

以上是关于栈———链表实现的主要内容,如果未能解决你的问题,请参考以下文章

数据结构与算法—数组栈和链表栈

数据结构与算法—数组栈和链表栈

C++中利用链表实现一个栈

深搜+栈==实现扁平化多级双向链表

栈的实现原理

算法漫游指北(第五篇):栈队列栈结构实现基于列表实现栈基于链表实现栈基于列表实现队列基于链表实现队列