链表栈实例(C语言)

链表栈基本操作

编译环境:VS !!
对应操作已写注解!!

#include <stdio.h>
#include <stdlib.h>
typedef char datatype;
//创建栈中的元素结构体(单链表)
typedef struct node
{
    datatype data;     //数据域
    struct node *next; //后继指针
} stacknode;
//创建栈的结构体
typedef struct
{
    stacknode *top; //栈的头指针
} linkstack;
//创建新结点
stacknode *buystacknode(datatype d)
{
    stacknode *newnode = (stacknode *)malloc(sizeof(stacknode));
    if (newnode == NULL)
    {
        printf("结点内存分配失败\n");
        exit(1);
    }
    newnode->data = d;
    newnode->next = NULL;
    return newnode;
}
//初始化栈
void initstack(linkstack *s)
{
    s->top = NULL;
}
//入栈
void push(linkstack *s, datatype d)
{
    stacknode *newnode = buystacknode(d);
    if (s->top == NULL)
    {
        /* code */
        s->top = newnode;
    }
    else
    {
        newnode->next = s->top;
        s->top = newnode;
    }
    printf("入栈成功!\n");
}
//出栈
void pop(linkstack *s)
{
    stacknode *cur = s->top;
    if (s->top == NULL)
    {
        /* code */
        printf("链表栈为空!");
        exit(1);
    }
    else
    {
        s->top = cur->next;
        free(cur);
        printf("出栈成功!\n");
    }
}
//打印栈元素
void printstack(linkstack *s)
{
    stacknode *cur = s->top;
    while (cur != NULL)
    {
        /* code */
        printf("%c", cur->data);
        cur = cur->next;
    }
    printf("\n");
}
//打印栈长度
void stacklength(linkstack *s)
{
    stacknode *cur = s->top;
    int j = 0;
    while (cur != NULL)
    {
        j++;
        cur = cur->next;
    }
    printf("该栈长度为:%d\n",j);
}
//测试
int main(int argc, char const *argv[])
{
    linkstack s;
    initstack(&s);
    push(&s, 'a');
    push(&s, 'b');
    push(&s, 'c');
    push(&s, 'd');
    printstack(&s);
    stacklength(&s);

    pop(&s);
    pop(&s);
    pop(&s);
    printstack(&s);
    stacklength(&s);
    return 0;
}

运行结果

在这里插入图片描述
该文章作为学习记录,水平有限。如有差错,请多多指点!!🐵

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值