資料結構-棧(C描述)

來源:互聯網
上載者:User

1.鏈式棧

stackli.h

typedef int ElementType;
#ifndef STACKLI_H_INCLUDED
#define STACKLI_H_INCLUDED
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
int IsEmpty(Stack S);
Stack CreateStack();
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(ElementType X, Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
#endif // STACKLI_H_INCLUDED

fatal.h
#ifndef FATAL_H_INCLUDED
#define FATAL_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#define Error(Str)        FatalError(Str)
#define FatalError(Str)   fprintf(stderr, "%s\n", Str), exit(1)
#endif // FATAL_H_INCLUDED

stackli.c
#include "stackli.h"
#include "fatal.h"
struct Node
{
    ElementType Element;
    PtrToNode   Next;
};
int IsEmpty(Stack S)
{
    return S->Next == NULL;
}
Stack CreateStack()
{
    Stack S;
    S = malloc(sizeof(struct Node));
    if(S == NULL)
        FatalError("Out of space!!!");
    S->Next = NULL;
    return S;
}
void MakeEmpty(Stack S)
{
    if(S == NULL)
        Error("Must use CreateStack first");
    else
        while(!IsEmpty(S))
            Pop(S);
}
void DisposeStack(Stack S)
{
    MakeEmpty(S);
    free(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;  /* Return value used to avoid warning */
}
void Pop(Stack S)
{
    PtrToNode FirstCell;
    if(IsEmpty(S))
        Error("Empty stack");
    else
    {
        FirstCell = S->Next;
        S->Next = S->Next->Next;
        free(FirstCell);
    }
}

相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。