動態數組實現線性表:結構體封裝基址、長度、容量。支持初始化、尾插、指定位置插入、指定位置刪除、遍歷顯示。
#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;
}
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;
}
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;
}