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

C 語言單向動態鏈表完整實作:初始化、建立、插入、刪除、查找、銷毀、輸出

     編輯:關於C語言

前言

單向鏈表是動態資料結構基礎。本文提供完整、可編譯的 C 語言實作,涵蓋所有核心操作,採用「帶頭結點」設計簡化邊界處理。

資料結構定義

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

typedef struct {
    Node *head;  /* 頭結點 (不存資料) */
    int size;
} List;

核心函數

初始化

void initList(List *list) {
    list->head = (Node *)malloc(sizeof(Node));
    list->head->next = NULL;
    list->size = 0;
}

建立 (尾插法)

void createList(List *list, int n) {
    Node *tail = list->head;
    for (int i = 0; i < n; i++) {
        int val; scanf("%d", &val);
        Node *newNode = (Node *)malloc(sizeof(Node));
        newNode->data = val;
        newNode->next = NULL;
        tail->next = newNode;
        tail = newNode;
        list->size++;
    }
}

插入 (第 pos 位置,0-based)

bool insertList(List *list, int pos, int val) {
    if (pos < 0 || pos > list->size) return false;
    Node *prev = list->head;
    for (int i = 0; i < pos; i++) prev = prev->next;
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->data = val;
    newNode->next = prev->next;
    prev->next = newNode;
    list->size++;
    return true;
}

刪除 (第 pos 位置)

bool deleteList(List *list, int pos) {
    if (pos < 0 || pos >= list->size) return false;
    Node *prev = list->head;
    for (int i = 0; i < pos; i++) prev = prev->next;
    Node *del = prev->next;
    prev->next = del->next;
    free(del);
    list->size--;
    return true;
}

查找 (回傳索引,未找到 -1)

int findList(List *list, int val) {
    Node *cur = list->head->next;
    int idx = 0;
    while (cur) {
        if (cur->data == val) return idx;
        cur = cur->next;
        idx++;
    }
    return -1;
}

輸出

void printList(List *list) {
    Node *cur = list->head->next;
    while (cur) {
        printf("%d ", cur->data);
        cur = cur->next;
    }
    printf("\n");
}

銷毀 (釋放所有節點)

void destroyList(List *list) {
    Node *cur = list->head;
    while (cur) {
        Node *next = cur->next;
        free(cur);
        cur = next;
    }
    list->head = NULL;
    list->size = 0;
}

主程式測試

int main() {
    List list; initList(&list);
    createList(&list, 5);      /* 輸入: 1 2 3 4 5 */
    printList(&list);          /* 1 2 3 4 5 */
    insertList(&list, 2, 99);  /* 1 2 99 3 4 5 */
    printList(&list);
    deleteList(&list, 0);      /* 2 99 3 4 5 */
    printList(&list);
    printf("Find 99: %d\n", findList(&list, 99)); /* 1 */
    destroyList(&list);
    return 0;
}

關鍵點總結

  • 頭結點統一插入/刪除邏輯,無需特判頭尾。
  • 所有 `malloc` 必配對 `free`,銷毀時遍歷釋放。
  • 插入/刪除先定位前驅節點 `prev`,再調整指標。
  • 查找/遍歷從 `head->next` 開始 (跳過頭結點)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved