• 练习3.21 一个数组两个站栈


    #include<stdio.h>
    #include<stdlib.h>
    struct Node;
    typedef struct Node *PtrToDStack;
    
    struct Node{
        int top1,top2;
        int Capacity;
        int  *Array;
    };
    
    PtrToDStack
    CreateStack( int Size )
    {
        PtrToDStack s;
        s = malloc( sizeof( struct Node ) );
        s->Array = malloc( sizeof( int ) * Size );
        s->Capacity = Size;
        return s;
    }
    
    void
    Initial( PtrToDStack s, int k )
    {
        if( k = 0 )
            s->top1 = -1;
        else
            s->top2 = s->Capacity;
    }
    
    int 
    IsEmpty( PtrToDStack s, int k ) 
    {
        if( k == 0 )
            return s->top1 == -1;
        else
            return s->top2 == Size;
    }
    
    int 
    IsFull( PtrToDStack s )
    {
        return s->top1 + 1 == s->top2;
    }
    
    void
    Push( PtrToDStack s, int k, int x )
    {
        if( !IsFull( s ) )
        {
            if( k == 0 )
                s->Array[ ++s->top1 ] = x;
            else
                s->Array[ --s->top2 ] = x;
        }
        else
            Error("stack is full");
    }
    
    void
    Pop( PtrToDStack s, int k )
    {
        if( k == 0 )
        {
            if( !IsEmpty( s, 0 ) )
                s->top1--;
            else
                Error("");
        }
        else
        {
            if( !IsEmpty( s, 1 ) )
                s->top2--;
            else
                Error("no ele")
        }
    }
    
    int 
    Top( PtrToDStack s, int k )
    {
        if( k == 0 )
        {
            if( !IsEmpty( s, k ) )
                return s->Array[ s->top1 ];
            else
                Error;
        }
        else
        {
            if( !IsEmpty(s,k) )
                return s->Array[ s->top2 ];
            else
                Error;
        }
    }
    View Code

    个人觉得在Top和Pop处IsEmpty有点冗杂,下次把两个指针都放进一个数组里面top[0],top[1]分别表示左栈和右栈

    代码的复用一下就高了

    单数组双栈迎面镇长的好处:可以最大化利用数组,减少溢出(我不造)

    我猜在push里面,IsFull的判断,如果满了,就发出溢出声明

  • 相关阅读:
    FJOI泛做
    [省选联考2022 ] 填树
    Public Round #2 C 背包
    【UER #7】天路
    [NOI2019] 机器人
    [省选联考2022] 序列变换
    ARC#139 D Priority Queue 2
    [省选联考2022]卡牌
    No Feign Client for loadBalancing defined. Did you forget to include springcloudstarterloadbalanc
    style加scoped属性的用途和原理
  • 原文地址:https://www.cnblogs.com/gabygoole/p/4645602.html
Copyright © 2020-2023  润新知