c++版:将两个有序顺序表合并为一个新的有序顺序表,并由函数返回结果顺序表
时间: 2024-09-30 12:11:27 浏览: 114
在C++中,你可以使用归并排序的思想来合并两个已排序的顺序表(也称作链表)。下面是一个简单的示例,展示如何创建一个名为`mergeSortedLists`的函数,它接受两个头节点作为参数,然后合并这两个列表并返回新的头部节点:
```cpp
#include <iostream>
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* mergeSortedLists(ListNode* l1, ListNode* l2) {
// 创建新链表的头节点和临时指针
ListNode* head = nullptr;
ListNode* tail = nullptr;
// 当l1或l2非空时,继续遍历
while (l1 && l2) {
// 如果l1的值小于l2,将其添加到新链表
if (l1->val <= l2->val) {
if (!head)
head = tail = l1;
else
tail->next = l1;
l1 = l1->next;
}
// 否则,将l2的值添加到新链表
else {
if (!head)
head = tail = l2;
else
tail->next = l2;
l2 = l2->next;
}
}
// 将剩余未处理的链表部分连接到新链表尾部
if (l1) tail->next = l1; // 如果l1还有元素,则直接连接
else if (l2) tail->next = l2; // 如果只有l2,同样连接
return head; // 返回合并后的链表头节点
}
// 测试代码(仅用于演示)
int main() {
// 初始化两个链表示例
ListNode* list1 = new ListNode(1);
list1->next = new ListNode(3);
list1->next->next = new ListNode(5);
ListNode* list2 = new ListNode(2);
list2->next = new ListNode(4);
list2->next->next = new ListNode(6);
// 调用合并函数并打印结果
ListNode* result = mergeSortedLists(list1, list2);
while (result != nullptr) {
std::cout << result->val << " ";
result = result->next;
}
std::cout << "\n";
delete result; // 清理内存
return 0;
}
```
当你运行这个程序,你会看到合并后的顺序链表输出为:`1 2 3 4 5 6`。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)