六個遞進項目:尾插建表、查找、刪除首節點、刪除指定值、建有序表、有序插入。每步提供參考代碼,強調指針操作邏輯。
struct Node { int data; Node* next; };
Node* head = nullptr;
// 1. 尾插建表
void make_list2() {
int n; Node *p, *q = nullptr;
while (cin >> n, n > 0) {
p = new Node; p->data = n; p->next = nullptr;
if (!head) head = p;
else q->next = p;
q = p;
}
}
// 2. 查找
void search(int x) {
for (Node* p = head; p; p = p->next)
if (p->data == x) { cout << "找到 " << x; return; }
cout << "未找到 " << x;
}
// 3. 刪除首節點
void delete_first() {
if (head) { Node* p = head; head = head->next; delete p; }
}
// 4. 刪除所有值為 x 的節點
void delete_node(int x) {
while (head && head->data == x) { Node* p = head; head = head->next; delete p; }
for (Node *p = head, *q = p ? p->next : nullptr; q; ) {
if (q->data == x) { p->next = q->next; delete q; q = p->next; }
else { p = q; q = q->next; }
}
}
// 5. 有序建表(遞增)
void make_list3() {
int n; while (cin >> n, n > 0) insert(n); // 復用 insert
}
// 6. 有序插入
void insert(int x) {
Node *t = new Node; t->data = x; t->next = nullptr;
if (!head || x <= head->data) { t->next = head; head = t; return; }
Node *p = head, *q = head->next;
while (q && x > q->data) { p = q; q = q->next; }
t->next = q; p->next = t;
}
p、q、t 指向。new 分配,delete 釋放,避免洩漏與野指針。