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

C语言编写链表程序运行时无限打印最后一个元素,求错误排查

问题错误定位与修复

你代码的核心问题有两处,都是内存和指针初始化的问题,正好对应你遇到的死循环打印最后一个元素的现象:

  • 第一处:main函数中创建哨兵头节点后,未初始化next指针为NULL,导致第一次调用joinLL找链表尾节点时,遍历逻辑完全异常。
  • 第二处:joinLL函数中新增节点未申请内存,直接操作野指针,属于未定义行为。绝大多数情况下新节点的next不会被正确赋值为NULL,甚至可能出现新节点的next指向自身的情况,遍历到这个节点就会进入死循环,反复打印同一个值。
  • 额外小问题:首次输入就为非数字时,你提前申请的头节点没有释放,会产生内存泄漏。

修正后的完整代码

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

typedef struct node {
    int data;
    struct node *next;
} NodeT;

void freeLL(NodeT *list) {
    NodeT *p, *temp;
    p = list;
    while (p != NULL) {
        temp = p->next;
        free(p);
        p = temp;
    }
}

void showLL(NodeT *list) {
    // 新增空链表判空处理,避免访问崩溃
    if (list->next == NULL) {
        printf("Done. The list is empty");
        return;
    }
    NodeT *temp = list;
    temp = temp->next;
    printf("Done. The list is ");
    printf("%d", temp->data);
    temp = temp->next;
    //遍历整个链表打印数据
    while (temp != NULL) {
        printf("-->");
        printf("%d", temp->data);
        temp = temp->next; 
    }
}

NodeT *joinLL(NodeT *list, int v) {
    NodeT *current = list;
    // 给新节点申请内存
    NodeT *new_node = (NodeT*)malloc(sizeof(NodeT));
    new_node->data = v;
    new_node->next = NULL;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = new_node;
    return new_node;
}

int main() {
    int data;
    NodeT *list = NULL;
    list = (NodeT *)malloc(sizeof(NodeT));
    // 初始化哨兵节点的next为NULL
    list->next = NULL;
    printf("Enter a number: ");
    if (scanf("%d", &data) != 1) {
        printf("Done. ");
        // 提前释放申请的头节点
        free(list);
    } else {
        joinLL(list, data);
        printf("Enter a number: ");
        while (1 == scanf("%d", &data)) { 
            joinLL(list, data);
            printf("Enter a number: ");
        }
        showLL(list);
        freeLL(list);
    }
    
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:54:03