結構定義
void create(Node** head) { *head = NULL; }
頭插法插入(不重複)
int delete(Node** head, int x) {
Node *p = *head, *prev = NULL;
while (p && p->data != x) { prev = p; p = p->next; }
if (!p) return 0; // 未找到
if (!prev) *head = p->next; // 刪頭
else prev->next = p->next;
free(p);
return 1;
}
查找
void show(Node* head) {
for (Node* p = head; p; p = p->next)
printf("%d ", p->data);
putchar('\n');
}
銷毀釋放
int main() {
Node* head; create(&head);
int n, x; scanf("%d", &n);
while (n--) { scanf("%d", &x); insert(&head, x); }
show(head);
scanf("%d", &x); delete(&head, x); show(head);
scanf("%d", &x); printf("%s\n", find(head,x)?"Found":"Not Found");
destroy(&head);
return 0;
}
注意事項
- 頭指針修改需傳
Node**。
malloc 失敗需檢查返回值。
- 刪除時先保存
next 再 free。
- 銷毀後置頭指針為 NULL,防野指針。