c语言 数据结构 栈 链式栈

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

//链式栈节点设计
struct node
{
    int num;           //数据域
    struct node *next; //指针域
};

//链式栈节点管理
typedef struct stack_list
{
    int count;        //链式栈的节点管理
    struct node *top; //链式栈节点指针
} sl, *psl;

//链式栈初始化
psl stack_list_init()
{
    psl mystack = malloc(sizeof(sl));
    if (mystack == NULL)
    {
        printf("申请链式栈失败\n");
        return NULL;
    }
    mystack->count = 0;
    mystack->top = NULL;
    return mystack;
}

//压栈
int push_stack_list(psl mystack, int num)
{
    struct node *newnode = malloc(sizeof(struct node));
    if (newnode == NULL) //判断新节点申请
    {
        printf("newnode error\n");
        return -1;
    }
    //新节点初始化
    newnode->num = num;
    newnode->next = NULL;
    //插入尾部
    newnode->next = mystack->top;
    //跟新新的节点
    mystack->top = newnode;
    // 节点长度加一
    mystack->count++;
    return 0;
}

//弹栈
int pop_stack_list(psl mystack, int *num)
{
    //判断是否为空
    if (mystack->count == 0)
    {
        printf("mystack empty\n");
    }
    //定义一个指针接收
    *num = mystack->top->num;
    //跟新新的节点
    mystack->top = mystack->top->next;
    // 节点减一
    mystack->count--;
    return 0;
}

int main(int argc, char const *argv[])
{
    psl mystack = stack_list_init();
    //压栈数据
    printf("压栈数据:");
    for (int i = 1; i <= 10; i++)
    {
        push_stack_list(mystack, i);
        printf("-%d", i);
    }
    printf("\n");

    //弹栈数据
    printf("弹栈数据:");
    int num;
    for (int i = 1; i <= 10; i++)
    {
        pop_stack_list(mystack, &num);
        printf("-%d", num);
    }
    printf("\n");
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值