數組需預先固定長度,難以應對元素數量不確定的場景,且可能造成內存浪費。鏈表採用動態內存分配,節點在內存中可不連續,按需申請釋放,靈活高效。
struct student {
long num; // 學號
float score; // 成績
struct student *next; // 指向下一節點的指針
};
關鍵點:
next 指針將離散節點串聯成鏈head,否則無法訪問鏈表next 置為 NULL 標記結束#include <stdlib.h>
#include <stdio.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student {
long num;
float score;
struct student *next;
};
int n; // 全局節點計數器
struct student *creat(void) {
struct student *head, *p1, *p2;
n = 0;
p1 = p2 = (struct student *)malloc(LEN);
scanf("%ld,%f", &p1->num, &p1->score);
head = NULL;
while (p1->num != 0) { // 以學號為0作為輸入結束標記
n++;
if (n == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = (struct student *)malloc(LEN);
scanf("%ld,%f", &p1->num, &p1->score);
}
p2->next = NULL;
return head;
}
void main() {
creat();
}
p1 指向新節點,p2 指向前一節點,便於連接headp2->next = p1 將新節點掛在尾部p2 = p1 更新尾指針next 置 NULL
每個節點包含數據域(num、score)和指針域(next),通過 next 串聯形成邏輯順序。
malloc 返回值(生產代碼必須加錯誤處理)next 置 NULL,導致遍歷越界scanf 格式字符串