首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C 語言鏈表合並去重邏輯錯誤修復與代碼優化

     編輯:程式設計疑難解答

原代碼主要問題

  1. Insert_1 邏輯錯誤:未正確處理頭節點後插入,導致鏈表斷裂。
  2. Combine 判重邏輯混亂:雙層循環未正確遍歷,且修改了源鏈表指針。
  3. PrintList 從頭節點 next 開始打印,但頭節點數據域未初始化。
  4. 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); }
}

測試結果

修正後可正確合並兩鏈表並去重,打印無誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved