本文实例为大家分享了C++合并两个排序的链表,供大家参考,具体内容如下
问题描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
1
2
3
4
5
6
7
|
struct ListNode { int val; struct ListNode *next; ListNode( int x) : val(x), next(NULL) { } }; |
方法一
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
|
class Solution { public : ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode* newList = NULL; //新链表头 ListNode* newListRear = NULL; //新链表尾 // 先处理某个链表为空的情形 if (pHead1 == NULL){ return pHead2; } if (pHead2 == NULL){ return pHead1; } // 把数值小的结点放入新链表,生成头节点 if (pHead1->val <= pHead2->val){ newList = pHead1; newListRear = pHead1; pHead1 = pHead1->next; } else { newList = pHead2 ; newListRear = pHead2; pHead2 = pHead2->next; } // 两表均不空的情形下,遍历 while (pHead1 != NULL && pHead2 != NULL) { if (pHead1->val <= pHead2->val) { newListRear->next =pHead1; newListRear = pHead1; pHead1 = pHead1->next; } else { newListRear->next =pHead2; newListRear = pHead2; pHead2 = pHead2->next; } } //某一表为空时,把另一表接入新表表尾 if (pHead1 == NULL) { newListRear->next = pHead2; } if (pHead2 == NULL) { newListRear->next = pHead1; } return newList; } }; |
方法二(递归思想)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class Solution { public : ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if (pHead1 == NULL){ return pHead2; } if (pHead2 == NULL){ return pHead1; } if (pHead1->val <= pHead2->val){ // pHead1为合并后的头节点 pHead1->next = Merge(pHead1->next, pHead2); return pHead1; } else { // pHead2 为合并后的头节点 pHead2->next = Merge(pHead1, pHead2->next); return pHead2; } } }; |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/francis_xd/article/details/82803905