写一个函数insert,用来向一个动态链表插入结点

写一个函数insert,用来向一个动态链表插入结点

点我看视频讲解+可运行代码,记得收藏视频,一键三连

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

typedef struct LNode
{
    int num;
    struct LNode *next;
} LNode;

void insert(int n, LNode *node)
{
    //创建新节点
    LNode *newNode = (LNode *)malloc(sizeof(LNode));
    newNode->num = n;

    LNode* next = node->next;

    // node ---> newNode  ---> next
    newNode->next = next;
    node->next = newNode;
}

LNode* creat(int n)
{
    LNode *head, *p;
    head = (LNode *)malloc(sizeof(LNode));
    p = head; //头节点为0 加上头节点共11个节点
    head->num = 0;
    head->next = NULL;
    for (int i = 1; i <= n; i++)
    {
        LNode *newNode = (LNode *)malloc(sizeof(LNode));
        newNode->num = i;
        newNode->next = NULL;
        p->next = newNode;
        p = p->next;
    }
    return head;
}

void printNode(LNode* head)
{
    LNode* p = head->next;
    while (p != NULL)
    {
        printf("num -> %dn", p->num);
        p = p->next;
    }
}

int main()
{
    LNode *head;
    int n;
    head = creat(10);
    printNode(head);
    printf("请输入需要插入的节点:n");
    scanf("%d", &n);
    insert(n, head);
    printf("链表的新内容:n");
    printNode(head);
    return 0;
}

运行截图:

写一个函数insert,用来向一个动态链表插入结点

原文链接: https://www.cnblogs.com/weiyidedaan/p/13331296.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    写一个函数insert,用来向一个动态链表插入结点

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/367558

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 下午5:50
下一篇 2023年3月2日 下午5:51

相关推荐