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

学生数据链表代码问题:Print函数漏打节点2首元素且多节点时无限循环

链表学生记录:打印异常与无限循环问题排查

兄弟,你这链表实现学生记录的问题我太熟了,大概率是踩中了两个经典的链表坑,我帮你拆解下:

1. 第二个节点名字无法打印的核心原因

最常见的就是字符串赋值方式错误:

  • 如果你在Insert函数里直接用newNode->first = first;这种方式给节点的名字赋值,这其实只是把指针指向了函数参数里的临时字符数组。等Insert函数执行完,这个临时数组的内存会被系统回收,后续访问第二个节点的first字段时,拿到的就是无效的内存地址,自然打不出正确的名字。
  • 正确的做法是用strcpy来拷贝字符串:strcpy(newNode->first, first);,前提是你的结构体里first是字符数组类型(比如char first[20];)。如果是char* first;类型,那得先给它分配内存:newNode->first = malloc(strlen(first)+1);,再用strcpy拷贝,不然会出现野指针问题。

另外还要检查节点初始化:创建新节点时,有没有遗漏对first字段的处理?比如忘记分配内存或者拷贝数据,都会导致打印异常。

2. 超过2个节点陷入无限循环的原因

这个几乎可以100%确定是尾节点的next指针没有置为NULL:
当你往链表末尾添加新节点时,如果没有把新节点的next设为NULL,那最后一个节点的next会指向一块随机的内存地址。在Print函数遍历链表时,循环条件如果是while(temp != NULL),就会因为找不到终止的NULL指针,一直遍历无效内存,陷入无限循环。

给你贴个正确的Insert函数示例(假设你的结构体和全局头节点是这样的):

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

typedef struct Student {
    char first[20];
    char last[20];
    float score;
    char zip[50];
    struct Student* next;
} Student;

Student* head = NULL; // 全局头节点

void Insert(char first[20], char last[20], float data, char zip[50]) {
    Student* newNode = (Student*)malloc(sizeof(Student));
    if (newNode == NULL) {
        printf("内存分配失败!\n");
        return;
    }
    // 正确拷贝字符串数据
    strcpy(newNode->first, first);
    strcpy(newNode->last, last);
    newNode->score = data;
    strcpy(newNode->zip, zip);
    // 关键:新节点的next必须设为NULL
    newNode->next = NULL;

    if (head == NULL) {
        head = newNode; // 链表为空时,新节点作为头节点
    } else {
        Student* temp = head;
        // 遍历到链表的最后一个节点(next为NULL的节点)
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = newNode; // 把新节点接到最后
    }
}

同时,你的Print函数遍历逻辑必须是这样的,才能正确终止:

void Print() {
    Student* temp = head;
    // 遍历到temp为NULL时停止,确保每个节点都能打印
    while (temp != NULL) {
        printf("姓名:%s %s,分数:%.2f,邮编:%s\n", temp->first, temp->last, temp->score, temp->zip);
        temp = temp->next;
    }
}

额外要检查的点

  • 如果你之前的Print函数用了while(temp->next != NULL)作为循环条件,那不仅会跳过最后一个节点,还会在尾节点next不为NULL时触发无限循环,一定要改成while(temp != NULL)。
  • 记得在程序结束或者删除节点时释放内存,避免内存泄漏,不过这是后续优化的问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:56:45