forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeTwoSortList.java
46 lines (38 loc) · 941 Bytes
/
MergeTwoSortList.java
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 {
// TC : O(n+m)
// SC: O(1)
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyNode = new ListNode(-1);
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode it1 =l1;
ListNode it2 =l2;
ListNode it = dummyNode;
while(it1!=null && it2!=null){
if(it1.val<it2.val){
it.next = it1;
it1 = it1.next;
it = it.next;
} else{
it.next = it2;
it2 =it2.next;
it = it.next;
}
}
while(it1!=null){
it.next = it1;
it1 = it1.next;
it = it.next;
}
while(it2!=null){
it.next = it2;
it2 = it2.next;
it = it.next;
}
return dummyNode.next;
}
}