-
Notifications
You must be signed in to change notification settings - Fork 0
/
剑指offer 16 合并两个排序的链表
51 lines (49 loc) · 1.43 KB
/
剑指offer 16 合并两个排序的链表
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
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
//递归
ListNode* Merge(ListNode* pHead1, ListNode* pHead2){
if(pHead1==NULL) return pHead2;
if(pHead2==nullptr) return pHead1;
if(pHead1->val>pHead2->val) {
pHead2->next=Merge(pHead1, pHead2->next);
return pHead2;
}
if(pHead1->val<pHead2->val) {
pHead1->next=Merge(pHead1->next, pHead2);
return pHead1;
}
}
// 循环
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
ListNode mergeHead = null;
ListNode current = null;
while(list1!=null && list2!=null){
if(list1.val <= list2.val){
if(mergeHead == null){
mergeHead = current = list1;
}else{
current.next = list1;
current = current.next;
}
list1 = list1.next;
}else{
if(mergeHead == null){
mergeHead = current = list2;
}else{
current.next = list2;
current = current.next;
}
list2 = list2.next;
}
}
if(list1 == null){
current.next = list2;
}else{
current.next = list1;
}
return mergeHead;