首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C語言實現單鏈表指定位置節點插入(無頭結點版)

     編輯:關於C

在《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;  // 頭指針未變
}

關鍵點總結

  • pos 語義:0 表示新節點成為第一個數據節點;size 表示追加到尾部。
  • 首節點特判:必須返回新頭指針,調用者 head = InsertToPosition(head, 0, val) 接收。
  • 循環變量 i 從 1 開始:對應 pos=1 即在第一個節點後插入(第二個位置)。
  • 內存安全:malloc 失敗直接返回原頭指針,不洩漏。

測試驗證

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 率大幅下降。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved