You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

链表头部插入节点后新节点未打印的代码错误排查与修正

链表头部插入节点问题修正

你的代码核心问题是函数参数传递方式错误:insert_first函数中的head是值传递,函数内部修改的只是head的副本,主函数里的原头指针根本没被更新,所以遍历的时候还是用原来的头节点,自然看不到新插入的节点。

两种修正方案:

方案一:使用指针的指针(推荐)

通过传入头指针的地址,让函数直接修改主函数中的头指针变量:

修改insert_first函数:

void insert_first(struct Node **head, int data) {
    struct Node *ptr = (struct Node *)malloc(sizeof(struct Node));
    ptr->data = data;
    ptr->next = *head;
    *head = ptr;
}

主函数中调用时改为:

insert_first(&head, 0);

方案二:返回新的头指针

让insert_first函数返回新的头节点,主函数接收返回值更新头指针:

修改insert_first函数:

struct Node* insert_first(struct Node *head, int data) {
    struct Node *ptr = (struct Node *)malloc(sizeof(struct Node));
    ptr->data = data;
    ptr->next = head;
    return ptr;
}

主函数中调用时改为:

head = insert_first(head, 0);

完整修正代码(方案一版本)

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

struct Node {
    int data;
    struct Node *next;
};

void traversal(struct Node *ptr) {
    while (ptr != NULL) {
        printf("%d\n", ptr->data);
        ptr = ptr->next;
    }
}

void insert_first(struct Node **head, int data) {
    struct Node *ptr = (struct Node *)malloc(sizeof(struct Node));
    ptr->data = data;
    ptr->next = *head;
    *head = ptr;
}

int main() {
    struct Node *head;
    struct Node *second;
    struct Node *third;
    struct Node *fourth;

    head = (struct Node *)malloc(sizeof(struct Node));
    second = (struct Node *)malloc(sizeof(struct Node));
    third = (struct Node *)malloc(sizeof(struct Node));
    fourth = (struct Node *)malloc(sizeof(struct Node));

    head->data = 10;
    head->next = second;

    second->data = 20;
    second->next = third;

    third->data = 30;
    third->next = fourth;

    fourth->data = 40;
    fourth->next = NULL;

    traversal(head);
    insert_first(&head, 0);
    printf("\n");
    traversal(head);

    // 释放动态分配的内存,避免内存泄漏
    struct Node *temp;
    while (head != NULL) {
        temp = head;
        head = head->next;
        free(temp);
    }

    return 0;
}

额外提示

代码中原来没有释放动态分配的内存,建议加上内存释放逻辑,避免程序运行时出现内存泄漏。

内容的提问来源于stack exchange,提问作者Devansh Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:30:42