顺序栈

#include<stdio.h>
#include<stdlib.h>

#define Max 50//栈中存放的最大元素个数

typedef struct 
{
    int elem[Max];//用来存放栈中元素的一维数组
    int top;//用来存放栈顶元素的下标,top为-1时,表示空栈
}Seqstack;

int initStack(Seqstack *S);//栈的初始化

int push(Seqstack *S);//进栈

void Pop(Seqstack *S);//出栈

int main(void)
{
    Seqstack S;
    int b;//接收函数返回值
    int a;//接收菜单输入值

    while (1)
    {
        printf("*********************\n");
        printf("1.InitStack\n");
        printf("2.Push\n");
        printf("3.Pop\n");
        printf("4.Exit\n");
        printf("*********************\n");

        printf("Please input the number of the menu:\n");
        scanf("%d", &a);

        switch (a)
        {
        case 1:b=initStack(&S);
            if (b == 1)
            {
                printf("InitStack Success!\n");
            }
            else
            {
                printf("Inint Fail\n");
            }
            break;

        case 2:b = push(&S);
            if (b == 0)
            {
                printf("Push Fail!\n");
            }
            if (b == 1)
            {
                printf("Push Success!\n");
            }
            break;

        case 3:Pop(&S);
            break;

        case 4:exit(0);
            break;

        default:printf("You input the figure is error\n");
            printf("Please input the figure again:\n");
            break;
        }
    }


    getchar();
    getchar();
    return 0;
}

int initStack(Seqstack *S)//栈的初始化
{
    S->top = -1;//构建一个空栈,第一次先将位置置为-1
    return 1;
}

int push(Seqstack *S)
{
    int a;
    int flag=1;//标志输入结束

    printf("Please input the figure that you want push(end by 0):\n");
    while (flag)
    {
        scanf("%d",&a);
        if (a==0)
        {
            flag = 0;
            continue;
        }
        if (S->top == Max - 1)//栈已满
        {
            return 0;
        }
        S->top++;//位置上移
        S->elem[S->top] = a;//将元素放在栈中
    }
    return 1;
}

void Pop(Seqstack *S)
{
    int a;

    while (S->top!=-1)//当栈顶不在最下面时继续
    {
        a = S->elem[S->top];
        S->top--;//位置下移
        printf("%d\t",a);
    }
    printf("\n");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值