-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeList.cpp
71 lines (70 loc) · 1.4 KB
/
MergeList.cpp
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
/*
* 题:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后
* 的链表满足单调不减规则
* struct ListNode{
* int val;
* struct ListNode* next;
* ListNode(int x):val(x),next(NULL){}
* };
*/
//递归解法
class solution{
public:
ListNode* Merge(ListNode* pHead1,ListNode* pHead2){
if(!pHead1) //若pHead1为空,则返回pHead2链表
return pHead2;
if(!pHead2) //若pHead2为空,则返回pHead1链表
return pHead1;
ListNode* pHead=NULL;
if(pHead1->val<=pHead2->val){ //递归
pHead=pHead1;
pHead->next=Merge(pHead1->next,pHead2);
}
else{
pHead=pHead2;
pHead->next=Merge(pHead1,pHead2->next);
}
return pHead;
}
}
//非递归解法
class solution{
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2){
if(!pHead1)
return pHead2;
if(!pHead2)
return pHead1;
ListNode* res=NULL;
ListNode* cur=NULL;
while(pHead1&&pHead2){
if(pHead1->val<=pHead2->val){
if(res==NULL){
res=pHead1;
cur=pHead1;
}
else{
cur->next=pHead1;
cur=cur->next;
}
pHead1=pHead1->next;
}
else{
if(res==NULL){
res=pHead2;
cur=pHead2;
}
else{
cur->next=pHead2;
cur=cur->next;
}
pHead2=pHead2->next;
}
}
if(!pHead1)
cur->next=pHead2;
else
cur->next=pHead1;
return res;
}
}