【数据结构】栈

顺序栈结构体的定义

typedef struct
{
    ElemType data[MAXSIZE]; //静态数组存放栈中
    int top;  //栈顶指针

}SqStack;

栈的初始化

void Init(SqStack* s)
{
    s->top=-1;  //初始化栈顶指针
    if(s->top=-1)
    printf("初始化栈成功\n");
    return;
}

入栈

void insert(SqStack* s,int x)
{
    if(s->top==MaxSize-1)
    {
        printf("栈满\n");
        return;
    }
    else
    s->top++;//top先+1再赋值
    s->data[s->top]=x;

    printf("元素“%d”入栈成功\n",x);

    return;
}

出栈

 出栈时x应为*x类型,用于记录出栈元素的值,入栈时无需记录入栈元素的值所以不加*,此代码直接采用打印方式

void Pop(SqStack* s)
{
    if(s->top==-1)
    {
        printf("栈空错误\n");
        return;
    }
    else
    printf("出栈元素:%d\n",s->data[s->top]);
    s->top--;

    return;
}

取栈顶元素

int Top(SqStack s)
{
    if(s.top==-1)
    {
        printf("栈空\n");
    }
    return s.data[s.top];
}

遍历栈内元素

void traversing(SqStack s)
{
    int i;
    if(s.top==-1)
    {
        printf("栈空报错");
        return;
    }
    else
    while(s.top!=-1)
    {
        printf("%d ",s.data[s.top]);
        s.top--;
    }
}

 销毁栈

void Destroy(SqStack* s)
{
    s->top=-1
}

 运行结果:

#include<stdio.h>
#define MaxSize 5

typedef struct SqStack{
    int data[MaxSize];
    int top;
}SqStack;

void Init(SqStack* s)
{
    s->top=-1;  //初始化栈顶指针
    if(s->top=-1)
    printf("初始化栈成功\n");
    return;
}

int Top(SqStack s)
{
    if(s.top==-1)
    {
        printf("栈空\n");
    }
    else
    return s.data[s.top];
}

void insert(SqStack* s,int x)
{
    if(s->top==MaxSize-1)
    {
        printf("栈满\n");
        return;
    }
    else
    s->top++;//top先+1再赋值
    s->data[s->top]=x;

    printf("元素“%d”入栈成功\n",x);

    return;
}

void Pop(SqStack* s)
{
    if(s->top==-1)
    {
        printf("栈空错误\n");
        return;
    }
    else
    printf("出栈元素:%d\n",s->data[s->top]);
    s->top--;

    return;
}

void traversing(SqStack s)
{
    int i;
    if(s.top==-1)
    {
        printf("栈空报错");
        return;
    }
    else
    while(s.top!=-1)
    {
        printf("%d ",s.data[s.top]);
        s.top--;
    }
}

void Destroy(SqStack* s)
{
    s->top=-1;
}

int main()
{
    SqStack s;
    Init(&s);
    printf("\n");

    int i,x;
    for(i=0;i<MaxSize;i++)
    {
        scanf("%d",&x);
        insert(&s,x);
    }
    printf("\n");

    printf("当前栈顶元素为:%d\n",Top(s));
    printf("\n");

    Pop(&s);
    printf("\n");

    printf("当前栈顶元素为:%d\n",Top(s));
    printf("\n");

    printf("遍历当前栈内元素:");
    traversing(s);
    printf("\n");

    printf("销毁栈:\n");
    Destroy(&s);

    printf("当前栈顶元素为:%d\n",Top(s));

    return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值