题目:将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的。
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72#include <iostream> using namespace std; struct myList { int val; myList* next; myList(int _val):val(_val),next(nullptr){} }; myList* merge(myList* l1, myList* l2) { // 当l1或l2为空时跳出 if (l1 == nullptr) return l2; if (l2 == nullptr) return l1; // 初始化伪头节点head(0) myList head(0); myList* node = &head; // l1为空或l2为空,跳出循环 while (l1 != nullptr && l2 != nullptr) { // 当l1.val<l2.val时,节点node的后继节点指定为l1,并l1向前走一步 if (l1->val < l2->val) { node->next = l1; l1 = l1->next; } else // 当l1.val>=l2.val时,节点node的后继节点指定为l2,并l2向前走一步 { node->next = l2; l2 = l2->next; } // 节点node向前走一步,即node=node->next node = node->next; } // 若l1!=null,将l1添加至节点node之后 if (l1 != nullptr) node->next = l1; else // 否则,将l2添加至节点node之后 node->next = l2; // 合并链表在伪头节点head之后,返回head.next return head.next; } int main() { // 创建节点 myList* node0 = new myList(1); myList* node1 = new myList(2); myList* node2 = new myList(4); myList* node3 = new myList(1); myList* node4 = new myList(3); myList* node5 = new myList(4); // 链表l1 node0->next = node1; node1->next = node2; node2->next = nullptr; // 链表l2 node3->next = node4; node4->next = node5; node5->next = nullptr; // 合并有序链表 auto node = merge(node0, node3); // 打印排序后的链表 while (node != nullptr) { cout << node->val << endl; node = node->next; } return 0; }
最后
以上就是欣喜海燕最近收集整理的关于C++实现算法题之合并有序链表的全部内容,更多相关C++实现算法题之合并有序链表内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复