顺序栈的一些操作

# include <stdio.h>
# include <malloc.h>
# define maxlen 100
typedef struct
{
    int data[maxlen];
    int top;//标注栈顶元素的位置,为数组下标

}SeqStack;
SeqStack * SetStack()
{
    SeqStack * S;
    S=(SeqStack *)malloc(sizeof(SeqStack));    
    S->top=-1;
    return S;

}
SeqStack * CreateStack(SeqStack * S,int n)
{
    S->top=0;
    while (S->top<n)
    {
        int x;
        scanf("%d", &x);
        S->data[S->top]=x;
        S->top++;
    }
    return S;
}
void print(SeqStack * S, int n)
{
    if (S->top==-1)
        printf("此栈为空!");
    else
    {
        S->top=0;
        while(S->top<n)
        {
           printf("%d",S->data[S->top]);
           printf("\n");
           S->top++;
        }
    }
}
int StackEmpty(SeqStack * S)
{
    if (S->top>=0)
        return 0;
    else
        return 1;
}
int StackFull(SeqStack * S)
{
    if (S->top<maxlen-1 && S->top>=0)
        return 0;
    else
        return 1;
}
int GetTop(SeqStack * S)
{
    if(S->top<=maxlen-1 && S->top>=0)
        return S->data[S->top];
    else
        return 1234;
}

void Push(SeqStack * S, int x)
{
    if (S->top<maxlen-1 && S->top>=-1)
    {
        S->top++;
        S->data[S->top]=x;
    }
    else
        printf("error");
}
void Pop(SeqStack * S)
{
    if (S->top>=0)
        S->top--;
    else
        printf("error");
}
SeqStack * InitStack(SeqStack * S)
{
    S->top=-1;
    return S;
}

void show(SeqStack * S)
{
    if (S->top==-1)
        printf("此栈为空!");
    else
        printf("此栈不为空!");
}

int main(void)
{
    SeqStack * H;

    H=SetStack();//建空顺序栈
    printf("请输入顺序栈中元素的个数:");

    int m;
    scanf("%d", &m);
    printf("请输入%d个元素:",m);
    H=CreateStack(H,m);//向顺序栈中输入元素
    printf("显示输入的元素:");
    print(H,m);

    int a;
    a=StackEmpty(H);//判断顺序栈是否为空
    if (a==1)
        printf("栈为空!");
    else
        printf("栈不为空!");

    int b;
    b=StackFull(H);//顺序栈判栈满
    if (b==1)
        printf("栈满!");
    else
        printf("栈不满!");

    int c;
    c=GetTop(H);//获取栈顶元素
    printf("栈顶元素是:");
    printf("%d", c);

    printf("请输入需要插入的栈顶元素:");
    int d;
    scanf("%d", &d);
    Push(H, d);
    printf("插入元素之后:");
    m=m+1;
    print(H,m);

    printf("请输出删除栈顶元素之后的结果:");
    Pop(H);
    m=m-1;
    print(H,m);

    H=InitStack(H);//置栈空
    printf("栈空是否为空:");
    show(H);
    
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值