在《C語言實現鏈表節點的刪除》基礎上,本文實現單鏈表(無頭結點)的指定位置插入操作。無頭結點意味著「首節點插入」需特判並更新頭指針,增加了邊界處理複雜度,是指針操作基本功的核心考點。
typedef struct Node {
int element;
struct Node* next;
} Node;
Node* InsertToPosition(Node* pHead, int pos, int x) {
// pos: 0-based,0=首節點前,size=尾部後
int size = SizeList(pHead);
if (pos < 0 || pos > size) {
printf("%s: pos=%d 非法(範圍 0~%d)\n", __FUNCTION__, pos, size);
return pHead;
}
Node* pInsert = (Node*)malloc(sizeof(Node));
if (!pInsert) return pHead;
pInsert->element = x;
pInsert->next = NULL;
// 情況1:插入首節點(pos==0)
if (pos == 0) {
pInsert->next = pHead;
printf("%s: 首節點前插入 x=%d 成功\n", __FUNCTION__, x);
return pInsert; // 新頭指針
}
// 情況2:中間/尾部插入
Node* pMove = pHead;
for (int i = 1; pMove; i++) {
if (i == pos) {
pInsert->next = pMove->next;
pMove->next = pInsert;
printf("%s: pos=%d 插入 x=%d 成功\n", __FUNCTION__, pos, x);
break;
}
pMove = pMove->next;
}
return pHead; // 頭指針未變
}
head = InsertToPosition(head, 0, val) 接收。int main() {
Node* head = NULL;
head = InsertToPosition(head, 0, 10); // 空表首插 -> 10
head = InsertToPosition(head, 1, 20); // 尾插 -> 10 20
head = InsertToPosition(head, 1, 15); // 中間插 -> 10 15 20
head = InsertToPosition(head, 0, 5); // 新頭 -> 5 10 15 20
head = InsertToPosition(head, 4, 25); // 新尾 -> 5 10 15 20 25
PrintList(head);
return 0;
}
對比可見,無頭結點版本需單獨處理 pos==0 並返回新頭指針,調用點極易忘記接收返回值導致 Bug。實際項目強烈建議使用帶頭結點單鏈表,插入邏輯統一為「找前驅、改指針」,無任何特判,代碼行數減少 30%+,Bug 率大幅下降。