C语言数组实现栈

学习笔记…

#include<stdio.h>
#include<stdlib.h>
#define Error( Str )    fprintf( stderr, "%s\n", Str ), exit( 1 )//可大量简化后面代码量
#define EmptyTOS -1
#define MinStackSize 5

typedef int ElementType;

typedef struct StackRecord{
    int TopOfStack;           //栈顶
    int Capacity;             //容量域
    ElementType *array;       //存储元素的数组
}*Stack;
//判断是否为空
int IsEmpty(Stack S)
{
    return S->TopOfStack == EmptyTOS;
}
//判断是否满栈
int IsFull(Stack S)
{
    return S->TopOfStack == S->Capacity - 1;
}
//清空栈
void MakeEmpty(Stack S)
{
    S->TopOfStack = EmptyTOS;//直接使TopOfStack为-1
}
//创建栈
Stack CreateStack(int MaxElement)
{
    Stack S;

    if(MaxElement < MinStackSize){
        Error("Stack Size is too small!");
    }
    S = malloc(sizeof(struct StackRecord));
    if(S == NULL)
        Error("Out of space!!!");
    S->array = malloc(sizeof(ElementType) * MaxElement);//开辟一个空间为sizeof(ElementType) * MaxElement位的空间
    if(S->array == NULL)
        Error("Out of space!");
    S->Capacity = MaxElement;
    MakeEmpty(S);
    return S;
}

void Push(ElementType X, Stack S)
{
    if(IsFull(S))
        Error("Full Stack");
    S->array[++S->TopOfStack] = X;//++S->TopOfSrack是 S->TopOfSrack立马增一
}

void Pop(Stack S)
{
    if(IsEmpty(S))
        Error("Empty Stack");
    S->TopOfStack--;
}

ElementType TopAndPop(Stack S)
{
    if(!IsEmpty(S))
        return S->array[S->TopOfStack--];
    else
    {
        Error("Empty Stack");
        return 0;
    }
}
//销毁栈
void DisposeStack(Stack S)
{
    if(S != NULL)
    {
        free(S->array);
        free(S);
    }
}
//返回栈顶元素
ElementType Top(Stack S)
{
    if(!IsEmpty(S))
        return S->array[S->TopOfStack];
    else
    {
        Error("Empty Stack");
        return 0;
    }
}
//遍历并打印栈
void TravalStack(Stack S)
{
    if(!IsEmpty(S)){
        for(; S->TopOfStack != EmptyTOS; S->TopOfStack--){
            printf("%d\n",Top(S));

        }
    }
    else
        Error("Empty Stack");
}

int main(){
    Stack S;

    S = CreateStack(10);
    Push(7,S);
    Push(6,S);
    Push(5,S);
    Push(4,S);
    Push(3,S);

    printf("%d\n",Top(S));

    Pop(S);
    Pop(S);

    TravalStack(S);

    DisposeStack(S);
    return 0;

}

在这里插入图片描述
用数组实现栈花费时间为很小的常数 应该尽可能写出各种错误检测,如果错误检测的代码量确实很大,可以省略

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值