-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge_two_sorted_list
44 lines (42 loc) · 1.1 KB
/
Merge_two_sorted_list
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
/*
Merge Two Sorted Lists
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:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (!l1) return l2;
if (!l2) return l1;
ListNode *dummyHead=new ListNode(INT_MIN);
ListNode *p=dummyHead;//p is used to track down the new list.
while(l1&&l2)
{
if (l1->val<=l2->val)
{
p->next=l1;
p=p->next;
l1=l1->next;
}
else
{
p->next=l2;
p=p->next;
l2=l2->next;
}
}
if (!l1) p->next=l2;
if (!l2) p->next=l1;
return dummyHead->next;
}
};
REMARK:
1 EASY. IDEA: Use a dummyHead to denote the first node in the new list and return dummyHead->next.It is not the only way though. Then use 2 pointers to walk though the 2 lists. done.
2. Time: O(n1+n2) where n1 and n2 are the length of the 2 lists repectively.