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

C语言链表问题:仅打印首节点,求错误排查及内存释放方法

问题分析与解决方案

一、链表仅能打印第一个节点的原因

你的代码里链表指针连接逻辑完全错误,导致实际链表只有head一个节点,second和third根本没被接入链表:

  • 原本head->next = second是正确的,但紧接着你又写了head->next = third,直接覆盖了head的后继节点,跳过了second;
  • 最后你再写head->next = NULL,直接把head的后继置空,等于链表彻底只剩head自己。

正确的链表连接逻辑应该是:

  • head的next指向second
  • second的next指向third
  • third的next指向NULL(标记链表结尾)

修正后的main函数关键代码:

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

second->data = 20;
second->next = third;  // 给second的后继赋值,而非修改head的后继

third->data = 30;
third->next = NULL;    // 最后一个节点的后继置空

二、malloc内存释放的时机与方法

内存释放要在你完全不再需要使用链表之后执行,也就是打印完链表之后。如果提前释放,后续访问链表会触发野指针错误。

你可以选择两种方式处理:

方法1:编写专门的释放函数

void freeList(struct Node *ptr) {
    struct Node *temp;
    while (ptr != NULL) {
        temp = ptr;
        ptr = ptr->next;
        free(temp);
    }
}

然后在main函数的printList(head);之后调用:freeList(head);

方法2:直接在main函数内处理

printList(head);

// 遍历释放内存
struct Node *temp;
while (head != NULL) {
    temp = head;
    head = head->next;
    free(temp);
}

完整修正后的代码

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

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

void printList(struct Node *ptr);
void freeList(struct Node *ptr);

int main(void)
{
    struct Node* head = NULL;
    struct Node* second = NULL;
    struct Node* third = NULL;

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

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

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

    third->data = 30;
    third->next = NULL;
    
    printList(head);
    freeList(head);
}

void printList(struct Node *ptr)
{
    struct Node *listPtr = ptr;
    int count = 1;
    if (listPtr == NULL)
    {
        printf("No elements in list.\n");
        return;
    }  
    while (listPtr!=NULL)
    {
        printf("element %d = %d\n",count,listPtr->data);
        listPtr = listPtr->next;
        count++;
    }
}

void freeList(struct Node *ptr) {
    struct Node *temp;
    while (ptr != NULL) {
        temp = ptr;
        ptr = ptr->next;
        free(temp);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:35:24