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

C 語言實現動態表格:鏈表與結構體的組合應用

     編輯:C 語言問答

需求分析

「建立表格」在 C 語言中通常指動態資料結構,支援增刪改查 (CRUD),而非靜態二維陣列。鏈表 是最基礎、最靈活的選擇。

核心資料結構設計

// 表格欄位定義 (範例:學生成績表)
typedef struct {
    int id;
    char name[32];
    float score;
} RowData;

// 鏈表節點
typedef struct Node {
    RowData data;       // 數據域
    struct Node *next;  // 指標域
} Node;

// 表格管理結構 (封裝頭尾指標、行數、欄位資訊)
typedef struct {
    Node *head;
    Node *tail;
    size_t row_count;
    // 可擴展:欄位名稱陣列、欄位類型、排序索引等
} Table;

核心操作 API 實現

1. 初始化與銷毀

void table_init(Table *t) { t->head = t->tail = NULL; t->row_count = 0; }

void table_destroy(Table *t) {
    Node *cur = t->head, *next;
    while (cur) { next = cur->next; free(cur); cur = next; }
    table_init(t);
}

2. 尾部插入 (新增行)


bool table_append(Table *t, const RowData *data) {
    Node *node = malloc(sizeof(Node));
    if (!node) return false;
    node->data = *data;
    node->next = NULL;

    if (!t->head) t->head = node;
    else t->tail->next = node;
    t->tail = node;
    t->row_count++;
    return true;
}

3. 按 ID 查找 (查詢)


Node* table_find_by_id(Table *t, int id) {
    for (Node *p = t->head; p; p = p->next)
        if (p->data.id == id) return p;
    return NULL;
}

4. 刪除行


bool table_delete_by_id(Table *t, int id) {
    Node *prev = NULL, *cur = t->head;
    while (cur) {
        if (cur->data.id == id) {
            if (prev) prev->next = cur->next;
            else t->head = cur->next;
            if (cur == t->tail) t->tail = prev;
            free(cur);
            t->row_count--;
            return true;
        }
        prev = cur;
        cur = cur->next;
    }
    return false;
}

5. 遍歷列印 (顯示表格)


void table_print(const Table *t) {
    printf("%-5s %-20s %s\n", "ID", "Name", "Score");
    printf("------------------------------\n");
    for (Node *p = t->head; p; p = p->next)
        printf("%-5d %-20s %.1f\n", p->data.id, p->data.name, p->data.score);
}

進階擴展:雙向鏈表與索引加速

  • 雙向鏈表:節點加 prev 指標,支援反向遍歷、O(1) 尾部刪除。
  • 跳表 / 平衡樹:大數據量下實現 O(log n) 查找/插入/刪除。
  • 動態陣列:若以查找為主、尾部增刪為主,realloc 擴容的動態陣列 (Vector) 緩存局部性更好,速度更快。

完整範例主程式

int main() {
    Table t; table_init(&t);
    table_append(&t, &(RowData){1, "Alice", 85.5});
    table_append(&t, &(RowData){2, "Bob", 92.0});
    table_print(&t);

    Node *found = table_find_by_id(&t, 1);
    if (found) printf("找到: %s\n", found->data.name);

    table_delete_by_id(&t, 1);
    table_print(&t);

    table_destroy(&t);
    return 0;
}

總結

C 語言無內建表格類型,但靈活運用 struct + 指標 + 動態記憶體,即可構建功能完整、高效能的表格系統。掌握鏈表增刪改查是 C 程式設計師的基本功,進階可封裝為通用容器庫。

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