實現通訊錄管理系統,核心功能:
#define MAX_SIZE 100
typedef struct {
char name[20];
char phone[15];
} Contact;
typedef struct {
Contact data[MAX_SIZE];
int length;
} SeqList;
// 初始化
void InitList(SeqList *L) { L->length = 0; }
// 插入(第i位置前插入x)
bool ListInsert(SeqList *L, int i, Contact x) {
if (i < 1 || i > L->length + 1) return false;
for (int j = L->length; j >= i; j--)
L->data[j] = L->data[j-1];
L->data[i-1] = x;
L->length++;
return true;
}
// 刪除第i個
bool ListDelete(SeqList *L, int i, Contact *e) {
if (i < 1 || i > L->length) return false;
*e = L->data[i-1];
for (int j = i; j < L->length; j++)
L->data[j-1] = L->data[j];
L->length--;
return true;
}
typedef struct Node {
Contact data;
struct Node *next;
} Node, *LinkList;
// 創建節點
Node* CreateNode(Contact x) {
Node *p = (Node*)malloc(sizeof(Node));
p->data = x;
p->next = NULL;
return p;
}
// 插入(在第i個節點前)
bool ListInsert(LinkList *L, int i, Contact x) {
Node *p = *L, *s = CreateNode(x);
int j = 0;
while (p && j < i-1) { p = p->next; j++; }
if (!p) return false;
s->next = p->next;
p->next = s;
return true;
}
| 操作 | 順序表 | 鏈表 |
|---|---|---|
| 查找 | O(1)下標 / O(n)值 | O(n) |
| 插入/刪除 | O(n)移動元素 | O(1)修改指針(找到位置後) |
| 空間 | 靜態分配/預分配 | 動態分配 |
| 適合場景 | 查多改少、數據量固定 | 增刪頻繁、數據量不定 |
數據結構學習核心:理解抽象數據類型(ADT),熟練基本操作實現。通訊錄是完美的入門項目。