首页 > 解决方案 > 如何将新节点添加到链表的开头?

问题描述

我正在尝试创建一个将节点添加到链表开头的函数。我已经创建了新节点并成功地将新节点指向了链表中的原始标题。但是,我不确定如何将我的新节点设置为链表的标题。

void insert_node(BURGER* header)
{
    BURGER* tp1;

    printf("Enter the details of record to be inserted in the format as\n");
    printf("<name>\n<popularity>\n");
    scanf_s("%s", &name, sizeof(name));
    scanf("%d", &popular);

    tp1 = make_node(name, popular);
    tp1->next = header;
    header = tp1;
    //printf("%d", tp1->next->popularity);

    printf("\n\n New record inserted at the start of the List\n");
}

亲切的问候

标签: c

解决方案


我认为你的思考过程是正确的。但是,该代码不起作用,因为您尝试将新节点设置为标头,而这不起作用,因为BURGER * header它是指向标头的指针的副本。所以你可以这样做:

void insert_node(BURGER** header)
{
    BURGER* tp1;

    printf("Enter the details of record to be inserted in the format as\n");
    printf("<name>\n<popularity>\n");
    scanf_s("%s", &name, sizeof(name));
    scanf("%d", &popular);

    tp1 = make_node(name, popular);
    tp1->next = *header;
    *header = tp1;
    //printf("%d", tp1->next->popularity);

    printf("\n\n New record inserted at the start of the List\n");
}

这样,您正在修改原始指针并更新链表的标题。


推荐阅读