Insert_1 邏輯錯誤:未正確處理頭節點後插入,導致鏈表斷裂。Combine 判重邏輯混亂:雙層循環未正確遍歷,且修改了源鏈表指針。PrintList 從頭節點 next 開始打印,但頭節點數據域未初始化。SoloDelete 釋放頭節點後未置空,可能導致野指針。// 尾插法構建鏈表
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
Node* tail = head;
int n, val;
scanf("%d", &n);
for (int i=0; idata = val; p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
// 合並去重:將 B 中不在 A 的元素插入 A
void combine(Node* A, Node* B) {
Node *p = B->next;
while (p) {
// 判斷 p->data 是否在 A 中
Node *q = A->next;
bool found = false;
while (q) {
if (q->data == p->data) { found = true; break; }
q = q->next;
}
if (!found) {
// 尾插到 A
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = p->data; newNode->next = NULL;
// 找到 A 尾部
Node *tail = A;
while (tail->next) tail = tail->next;
tail->next = newNode;
}
p = p->next;
}
}
// 打印
void printList(Node* head) {
Node* p = head->next;
while (p) { printf("%d ", p->data); p = p->next; }
printf("\n");
}
// 釋放
void freeList(Node* head) {
Node* p = head;
while (p) { Node* tmp = p; p = p->next; free(tmp); }
}
修正後可正確合並兩鏈表並去重,打印無誤。