/* 栈的数组实现声明 */
struct StackRecord;
typedef struct StackRecord *Stack;

#define MinSstackSize 5
#define EmptyTOS -1
struct StackRecord
{
    int Capacity;
    int TopOfStack;
    ElementType *Array;
};

/* 栈的创建-数组实现 */
Stack
CreateStack( int MaxElements )
{
    Stack S;
    if( MaxElements < MaxStackSize ) 
        ERROR("stack is too small");
    S = malloc(sizeof( struct StackRecord ));
    if( S == NULL )
        FatalError("out of Space");
    S->Array = malloc(sizeof(ElementType) * MaxElements);
    if( S->Array == NULL )
        Fatalerror("out of space");
    S->Capacity = MaxElements;
    MakeEmpty( S );
    return S;
}
/* 数组事项创建空栈的例程 */
void
MakeEmpty( Stack S )
{
    S->TopOfStack =EmptyTOS;
}
/* 释放栈 */
void
DisposeStack( Stack S )
{
    if(S != NULL ){
    free( S->Array );
    free( S );
    }
}
/* 监测一个栈是否空栈的的例程 */
int 
IsEmpty( Stack S )
{
    return S->TopOfStack == -1;
}
/* 判断栈满 */
int
IsFull( Stack S )
{
    return TopOfStack == Capacity - 1;
}
/* 进栈的例程 */
void
Push( ElementType X, Stack S)
{
    if( IsFull( S ) )
        ERROR("stack is full");
    else
        S->Array[ ++S->TopOfStack ] = X;
}
/* 返回栈顶的例程 */
ElementType
Top( Stack S )
{
    if( IsEmpty( S ) ){
        ERROR("stack is empty");
        return 0;//避免无
    }
    else
        return S->Array[ S->TopOfStack ];
}

/* Pop操作 */
/* TopOfStack相当于指向栈顶元素的指针 */
/* TopOfStack-- 只是让指针下移,但是没消除原来数据,下次要Push就直接覆盖*/
/* 并且S->Array 的栈空间设定好了,即MaxElements */

void
Pop( Stack S )
{
    if( IsEmpty( S ) )
        ERROR("Empty stack");
    else
        S->TopOfStack--;
}
ElementType
PopAndTop( Stack S )
{
    if( !IsEmpty( S ) )
    return S->Array[ S->TopOfStack-- ];
}
View Code

相关文章: