溫馨提示×

C++單鏈表的合并操作如何實施

c++
小樊
85
2024-07-16 20:25:47
欄目: 編程語言

在C++中,可以通過創(chuàng)建一個新的鏈表來合并兩個已有的單鏈表。具體步驟如下:

  1. 創(chuàng)建一個新的鏈表用于存儲合并后的結(jié)果。
  2. 遍歷第一個鏈表,依次將節(jié)點復(fù)制到新鏈表中。
  3. 再遍歷第二個鏈表,將節(jié)點依次復(fù)制到新鏈表的末尾。
  4. 最終返回新鏈表即為兩個單鏈表合并后的結(jié)果。

下面是一個示例代碼:

#include <iostream>

struct Node {
    int data;
    Node* next;
    Node(int val) : data(val), next(nullptr) {}
};

Node* mergeLists(Node* l1, Node* l2) {
    Node* dummy = new Node(0);
    Node* cur = dummy;

    while (l1 && l2) {
        if (l1->data < l2->data) {
            cur->next = l1;
            l1 = l1->next;
        } else {
            cur->next = l2;
            l2 = l2->next;
        }
        cur = cur->next;
    }

    cur->next = l1 ? l1 : l2;

    Node* mergedList = dummy->next;
    delete dummy;
    return mergedList;
}

void printList(Node* head) {
    Node* cur = head;
    while (cur) {
        std::cout << cur->data << " ";
        cur = cur->next;
    }
    std::cout << std::endl;
}

int main() {
    Node* l1 = new Node(1);
    l1->next = new Node(3);
    l1->next->next = new Node(5);

    Node* l2 = new Node(2);
    l2->next = new Node(4);
    l2->next->next = new Node(6);

    Node* mergedList = mergeLists(l1, l2);
    printList(mergedList);

    return 0;
}

在上面的示例代碼中,我們首先定義了一個Node結(jié)構(gòu)體表示鏈表節(jié)點,然后實現(xiàn)了mergeLists函數(shù)來合并兩個有序單鏈表。最后在main函數(shù)中創(chuàng)建兩個有序單鏈表,并調(diào)用mergeLists函數(shù)進行合并,然后輸出合并后的鏈表。

0