在C++中,可以通過創建一個新的鏈表來合并兩個已有的單鏈表。具體步驟如下:
下面是一個示例代碼:
#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
結構體表示鏈表節點,然后實現了mergeLists
函數來合并兩個有序單鏈表。最后在main
函數中創建兩個有序單鏈表,并調用mergeLists
函數進行合并,然后輸出合并后的鏈表。