练习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的判断,如果满了,就发出溢出声明

posted @ 2015-07-14 15:34  Gabyler  阅读(212)  评论(0编辑  收藏  举报