首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C語言無頭單鏈表創建與輸出:常見錯誤與修正版

     編輯:程式設計疑難解答

原代碼核心問題

  1. 創建邏輯錯誤: 首節點未正確鏈接,r=0導致空指針解引用
  2. 輸入處理缺陷: scanf("%c") 讀取殘留換行符
  3. 輸出函數假設有頭節點: p=L->next 跳過首節點

修正版:無頭節點單鏈表完整實現

#include 
#include 

typedef int ElemType;
typedef struct Node {
    ElemType data;
    struct Node *next;
} Node;

// 尾插法創建(無頭節點)
Node* CreateList(ElemType a[], int n) {
    if (n <= 0) return NULL;
    Node *head = (Node*)malloc(sizeof(Node));
    head->data = a[0];
    head->next = NULL;
    Node *tail = head;
    for (int i = 1; i < n; i++) {
        Node *p = (Node*)malloc(sizeof(Node));
        p->data = a[i];
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
    return head;
}

// 輸出鏈表
void DispList(Node *head) {
    Node *p = head;
    while (p) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

// 釋放鏈表
void FreeList(Node *head) {
    Node *p = head;
    while (p) {
        Node *tmp = p;
        p = p->next;
        free(tmp);
    }
}

int main() {
    ElemType a[10] = {1,2,3,4,5,6,7,8,9,0};
    Node *L = CreateList(a, 10);
    DispList(L);
    FreeList(L);
    return 0;
}

關鍵點對比

場景有頭節點無頭節點
創建返回頭節點指針首數據節點指針
插入首位統一邏輯需特判修改head指針
刪除首位統一邏輯需特判修改head指針
代碼複雜度較低較高

進階建議

  • 教學/面試常考無頭節點,工程實踐強烈推薦帶頭節點
  • 封裝List結構體包含head, tail, size,操作更安全
  • 使用valgrind --leak-check=full檢測內存洩漏
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved