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

为何我用C语言遍历练手链表时会陷入无限循环?

解决链表遍历无限循环的问题

嘿,我一眼就揪出你代码里的问题啦!你遇到的无限循环根本不是最后一个节点没指向NULL,而是遍历链表的逻辑写错了,咱们一步步拆解来看:

1. 遍历函数的核心错误

你的discover函数里,循环内更新current的代码完全写错了:

current = head->next;

这会导致current永远死死盯着链表的第二个节点,根本不会往后移动,自然永远碰不到NULL,直接陷入无限循环!

正确的写法应该是让current移动到它自己的下一个节点:

current = current->next;

2. 额外的小优化(非循环原因,但更规范)

你在main里一开始malloc了一个空节点,但这个节点的val没初始化,其实完全可以直接把head初始化为NULL——add_first函数会自动处理第一个节点的next指向NULL,这样代码更简洁也更符合链表的常规写法:

int main(){
    noeud* head = NULL; // 直接初始化为NULL,省去多余节点
    head = add_first(head, 5);
    head = add_first(head, 4);
    head = add_first(head, 3);
    head = add_first(head, 8);
    discover(head);
    return 0;
}

修正后的完整代码

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

typedef struct noeud { 
    int val; 
    struct noeud *next; 
} noeud; 

noeud* add_first(noeud* head, int val){ 
    noeud* p = malloc(sizeof(noeud)); 
    if(p == NULL){ 
        puts("ERROR ALLOCATING NODE "); 
        exit(-1); 
    } else{ 
        p->val = val; 
        p->next = head; 
    } 
    return p; 
} 

void discover(noeud* head){ 
    noeud* current = head; 
    while(current != NULL){ 
        printf("---|%d|-|%p|---\n",current->val, current->next); // 加换行让输出更清晰
        current = current->next; // 这里是修正的核心!
    } 
} 

int main(){ 
    noeud* head = NULL; 
    head = add_first(head, 5); 
    head = add_first(head, 4); 
    head = add_first(head, 3); 
    head = add_first(head, 8); 
    discover(head); 
    return 0; 
}

运行这段代码,你就能正常遍历整个链表,不会再陷入无限循环啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:44:24