原代碼在 main 中連續調用兩次 creat():
creat(); // 第一次調用,返回值被丟棄
head = creat(); // 第二次調用,實際使用的鏈表
這導致第一次創建的鏈表內存洩漏,且輸入數據被消耗兩次,致使第二次創建時無有效輸入,打印函數無內容輸出。
creat() 調用,僅保留 head = creat();。#include <stdio.h>、#include <stdlib.h>。next 開始遍歷,避免打印頭節點的無效數據。int main() {
student *head = creat(); // 單次調用
print(head);
return 0;
}
void print(student *head) {
student *p = head->next; // 跳過頭節點
while (p != NULL) {
printf("%d %f\n", p->num, p->score);
p = p->next;
}
}
使用調試器單步執行,觀察鏈表節點創建與鏈接過程;輸入數據時注意結束標記(如 0)的處理邏輯。