Skip to content

Commit 5a4fb98

Browse files
authored
Create MergeTwoSortedLL.java
0 parents  commit 5a4fb98

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

MergeTwoSortedLL.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
13+
// handling edge edge cases
14+
// if only list 2 exists return list 2
15+
if(l1==null)
16+
return l2;
17+
// if only list 1 exists return list 1
18+
if(l2==null)
19+
return l1;
20+
// if no list exists return null
21+
if(l1==null && l2 == null)
22+
return null;
23+
// creating two pointers to keep track new sorted linked list
24+
ListNode head = null;
25+
ListNode tail = null;
26+
27+
while(l1 != null && l2 != null){
28+
if(l1.val<l2.val){
29+
if(head == null)
30+
head = tail = l1;
31+
else{
32+
tail.next = l1;
33+
tail = l1;
34+
}
35+
l1= l1.next;
36+
}
37+
else{
38+
if(head == null)
39+
head = tail = l2;
40+
else{
41+
tail.next = l2;
42+
tail = l2;
43+
}
44+
l2 = l2.next;
45+
}
46+
}
47+
48+
// now checking adding the remaining l1 or l2 list;
49+
// making tail .next = null
50+
if(tail!=null)
51+
tail.next = null;
52+
if(l1!=null)
53+
tail.next = l1;
54+
if(l2 != null)
55+
tail.next = l2;
56+
return head;
57+
58+
59+
60+
}
61+
}

0 commit comments

Comments
 (0)