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

數據結構:線性表順序存儲結構完整實現 (增刪改查)

     編輯:關於C語言

數據結構:線性表順序存儲結構完整實現 (增刪改查)

動態數組實現線性表:結構體封裝基址、長度、容量。支持初始化、尾插、指定位置插入、指定位置刪除、遍歷顯示。

結構定義

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct {
    int *base;      // 動態數組基址
    int length;     // 當前有效長度
    int capacity;   // 分配容量
} SeqList;

核心操作

初始化

void init(SeqList *L, int cap) {
    L->base = (int*)malloc(cap * sizeof(int));
    if (!L->base) { printf("內存失敗\n"); exit(-1); }
    L->length = 0;
    L->capacity = cap;
}

尾插

bool append(SeqList *L, int val) {
    if (L->length >= L->capacity) return false;
    L->base[L->length++] = val;
    return true;
}

插入 (位置 pos 1-based)

bool insert(SeqList *L, int pos, int val) {
    if (L->length >= L->capacity) return false;
    if (pos < 1 || pos > L->length + 1) return false;
    for (int i = L->length - 1; i >= pos - 1; i--)
        L->base[i+1] = L->base[i];
    L->base[pos-1] = val;
    L->length++;
    return true;
}

刪除 (位置 pos 1-based,返回被刪值)

bool delete(SeqList *L, int pos, int *val) {
    if (L->length == 0) return false;
    if (pos < 1 || pos > L->length) return false;
    *val = L->base[pos-1];
    for (int i = pos; i < L->length; i++)
        L->base[i-1] = L->base[i];
    L->length--;
    return true;
}

遍歷

void show(SeqList *L) {
    if (L->length == 0) { printf("空表\n"); return; }
    for (int i = 0; i < L->length; i++) printf("%d\t", L->base[i]);
    printf("\n");
}

主函數測試

int main() {
    SeqList L;
    int val;
    init(&L, 6);
    append(&L, 10); append(&L, 20); append(&L, 30);
    append(&L, 40); append(&L, 50);
    show(&L);           // 10 20 30 40 50
    insert(&L, 2, 5);   // 位置2插5
    show(&L);           // 10 5 20 30 40 50
    delete(&L, 2, &val);
    printf("刪除:%d\n", val);  // 5
    show(&L);           // 10 20 30 40 50
    return 0;
}

運行結果

線性表:10	20	30	40	50
插入元素後的線性表:10	5	20	30	40	50
刪除的元素:5
刪除元素後的線性表:10	20	30	40	50

擴展:動態擴容

bool ensure_capacity(SeqList *L) {
    if (L->length < L->capacity) return true;
    int new_cap = L->capacity * 2;
    int *new_base = realloc(L->base, new_cap * sizeof(int));
    if (!new_base) return false;
    L->base = new_base;
    L->capacity = new_cap;
    return true;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved