zoukankan      html  css  js  c++  java
  • 数据结构与算法分析 3.23 — 用一个数组实现三个(多个)栈

    一、题目

        用一个数组实现三个(或多个)栈

    二、解答

        用一个数组实现三个乃至多个栈,如果想使用一个数组构造两个栈的思想则行不通;

        考虑使用静态链表,数组结点中存在两个域,关键字域与指示栈的前驱的游标,则可以使三个栈可以用一个数组表示;

        ADT的关键术语:

        Capacity: 数组的容量;

        Size: 数组已经存储的数据元素个数;

        Top_Fst:First栈的栈顶;

    三、代码

    struct Node;
    typedef struct Node ElementType;
    typedef struct StackRecord * Stack;
    
    struct Node
    {
        Type Key;
        int Pre;
    };
    
    struct StackRecord
    {
        int Capacity;
        int Size;
        int Top_Fst;
        int Top_Snd;
        int Top_Trd;
        ElementType *Array;
    };
    
    Stack CreateStack( int MaxElements );
    int IsEmpty_Fst( Stack S );
    int IsFull( Stack S );
    void Push_Fst( Type Key, Stack S );
    Type Pop_Fst( Stack S );
    void MakeEmpty( Stack S );
    void DisposeStack( Stack S );
    
    Stack CreateStack( int MaxElements )
    {
        Stack S;
    
        S = (Stack)malloc( sizeof(struct StackRecord) );
        if ( S == NULL )
        {
            printf( "Out of space" );
            return NULL;
        }
    
        S->Array = (ElementType *)malloc( sizeof(ElementType) * MaxElements );
        if ( S->Array == NULL )
        {
            printf( "Out of space" );
            return NULL;
        }
    
        S->Capacity = MaxElements;
        MakeEmpty(S);
    
        return S;
    }
    
    int IsEmpty_Fst( Stack S )
    {
        return S->Top_Fst == -1;
    }
    
    int IsFull( Stack S )
    {
        return S->Size == S->Capacity;
    }
    
    void MakeEmpty( Stack S )
    {
        if ( S != NULL )
        {
            S->Size =0;
            S->Top_Fst = -1;
            S->Top_Snd = -1;
            S->Top_Trd = -1;
        }
    }
    
    void Push_Fst( Type Key, Stack S )
    {
        int TmpCell;
    
        if ( IsFull(S) )
            printf( "Stack is full" );
        else
        {
            TmpCell = S->Top_Fst;
            S->Top_Fst = S->Size;
            S->Array[S->Top_Fst].Key = Key;
            S->Array[S->Top_Fst].Pre = TmpCell;
            S->Size++;
        }
    }
    
    Type Pop_Fst( Stack S )
    {
        int TmpCell;
    
        if ( IsEmpty_Fst(S) )
            printf( "Stack is empty" );
        else
        {
            TmpCell = S->Top_Fst;
            S->Top_Fst = S->Array[TmpCell].Pre;
            S->Size--;
        }
    
        return S->Array[TmpCell].Key;
    }
    
    void DisposeStack( Stack S )
    {
        if ( S != NULL )
        {
            free( S->Array );
            free( S );
        }
    }
  • 相关阅读:
    怎样练习一万小时
    新闻的未来
    有些人无缘再见,却一生想念
    媒体该如何展示事实之美?
    传统媒体:广告都去哪儿了?
    一线从业者干货分享:不做“忧伤”的媒体人
    整理者与信息平台
    把媒体当手段还是当目的?
    媒体人转身,转身去哪里?
    腾讯新闻的海量服务
  • 原文地址:https://www.cnblogs.com/tallisHe/p/4007461.html
Copyright © 2011-2022 走看看