forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeTwoSortedList.cpp
96 lines (83 loc) · 2.31 KB
/
mergeTwoSortedList.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Source : https://oj.leetcode.com/problems/merge-two-sorted-lists/
// Author : Hao Chen
// Date : 2014-07-06
/**********************************************************************************
*
* Merge two sorted linked lists and return it as a new list. The new list should be
* made by splicing together the nodes of the first two lists.
*
**********************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
Solution(){
srand(time(NULL));
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (random()%2){
return mergeTwoLists01(l1, l2);
}
return mergeTwoLists02(l1, l2);
}
ListNode *mergeTwoLists01(ListNode* head1, ListNode* head2){
ListNode *p1 = head1, *p2=head2;
static ListNode dummy(0);
dummy.next = p1;
ListNode *prev = &dummy;
while(p1 && p2){
if(p1->val < p2->val){
prev = p1;
p1 = p1->next;
}else{
prev->next = p2;
p2 = p2->next;
prev = prev->next;
prev->next = p1;
}
}
if (p2){
prev->next = p2;
}
return dummy.next;
}
ListNode *mergeTwoLists02(ListNode *l1, ListNode *l2) {
ListNode *l=NULL, *p=NULL;
while (l1!=NULL && l2!=NULL ){
ListNode *n=NULL;
if (l1->val < l2-> val){
n = l1;
l1=l1->next;
}else{
n = l2;
l2=l2->next;
}
if (l==NULL){
l = p = n;
}else{
p->next = n;
p = p->next;
}
}
ListNode* rest = l1 ? l1 :l2;
l = mergeTheRest(rest, l, p);
return l;
}
private:
ListNode* mergeTheRest(ListNode* l, ListNode*head, ListNode* tail){
if (l){
if (head && tail ){
tail->next = l;
}else{
head = l;
}
}
return head;
}
};