栈--数组实现



#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值