首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >C语言写简单的单项链表

C语言写简单的单项链表

作者头像
心跳包
发布2020-08-31 15:00:28
发布2020-08-31 15:00:28
1.8K00
代码可运行
举报
运行总次数:0
代码可运行
代码语言:javascript
代码运行次数:0
运行
复制
/* 基本数据结构的定义以及函数的声明 */
typedef int ElemType;

typedef struct Node
{
    ElemType elem;
    struct Node* next;
} Node, * NodePtr, **ForwardList;

NodePtr createNode(ElemType x);

void showList(ForwardList lst);

void destroyList(ForwardList lst);

// 创建元素为x的节点并插入到节点where后面
// 若where为NULL, 则插入到链表lst的首部作为首节点
// 返回新节点的指针
NodePtr insertAfterNode(NodePtr where, ElemType x,
        ForwardList lst);
代码语言:javascript
代码运行次数:0
运行
复制
/* 链表相关函数的具体实现 */
NodePtr createNode(ElemType x)
{
    NodePtr pNode = (NodePtr) malloc(sizeof(Node));
    if (pNode == NULL) {
        perror("malloc");
        exit(1);
    }

    pNode->elem = x;
    pNode->next = NULL;
    return pNode;
}

NodePtr insertAfterNode(const NodePtr where,
        ElemType x, ForwardList lst)
{
    NodePtr pNode = createNode(x);

    if (where == NULL) {
        *lst = pNode;
    } else {
        pNode->next = where->next;
        where->next = pNode;
    }

    return pNode;
}

void showList(ForwardList lst)
{
    printf("显示链表: ");
    NodePtr curr = *lst;
    while (curr->next != NULL) {
        printf("%d->", curr->elem);
        curr = curr->next;
    }
    printf("%d\n", curr->elem);
}

void destroyList(ForwardList lst)
{
    printf("销毁链表: ");
    NodePtr curr = *lst;
    while (curr != NULL) {
        NodePtr next = curr->next;
        printf("%d ", curr->elem);
        free(curr);
        curr = next;
    }
    printf("\n");
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/05/25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档