栈--数组实现



#include "stdio.h"
#include "stdlib.h"
//好好写代码
#define MIN_STACK_SIZE  5

typedef struct StackRecord *Stack;

struct StackRecord 
{
    int Capacity;
    int Top;
    int *Array;
};

int IsEmpty(Stack SS);

int IsFull(Stack SS);

Stack CreateStack(int MaxElements);

void DisposeStack(Stack SS);//回收栈

void MakeEmpty(Stack SS);

void Push(int X,Stack SS);

int Top(Stack SS);

void Pop(Stack SS);

int PopAndTop(Stack SS);

int IsEmpty(Stack SS)
{
    return SS->Top==0;
}

int IsFull(Stack SS)
{
    return SS->Top==SS->Capacity ;   //指针在存放数据的下一位,并不是存放数据的
                                     //那一位
}

void MakeEmpty(Stack SS)
{
    SS->Top=0;
}

Stack CreateStack(int MaxElements)
{
    if (MaxElements<MIN_STACK_SIZE){
        printf("it is too small\n");
        return 0;
    }
    else{
        Stack SS=malloc(sizeof(struct StackRecord));
        if (SS==NULL){
            printf(" error\n");
            return 0;
        }
        else{
            SS->Array=malloc(sizeof(int)*MaxElements);
            SS->Capacity=MaxElements;
            MakeEmpty(SS);
            return SS;
        }
    }
}

void DisposeStack(Stack SS)
{
    if (SS==NULL){
        printf("it is empty\n");
    }
    else{
        free(SS->Array);
        free(SS);
    }
}

void Push(int X,Stack SS)
{
    if (IsFull(SS)){
        printf("it is full\n");
    }
    else{
        SS->Array[SS->Top++]=X;
    }
}

int Top(Stack SS)
{
    if (IsEmpty(SS)){
        printf("error\n");
        exit(1);
    }
    else    {
        return SS->Array[SS->Top-1];
    }
}

void Pop(Stack SS)
{
    if (IsEmpty(SS)){
        printf("it is empty\n");
        exit(1);
    }
    else    {
        --(SS->Top);
    }
}

int PopAndTop(Stack SS)
{
    if (IsEmpty(SS)){
        printf("it is empty\n");
        exit(1);
    }
    else{
        return SS->Array[--SS->Top];
    }
}

int main()
{
    Stack SS=CreateStack(10);
    int i;
    for (i=0;i<10;i++){
        Push(i,SS);
    }
    while (!IsEmpty(SS)){
        printf("%d\n",PopAndTop(SS));
    }
    printf("\n");
    return 0;
}


你可能感兴趣的:(栈--数组实现)