Skip to content

Commit 59e8617

Browse files
authored
Merge pull request neetcode-gh#67 from vrindavan/main
21-Merge-Two-Sorted-Lists Recursion alernative solution
2 parents 07d245a + 2d375c2 commit 59e8617

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

java/21-Merge-Two-Sorted-Lists.java

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,35 @@ public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
2727
prev.next = list1 != null ? list1 : list2;
2828
return root.next;
2929
}
30-
}
30+
}
31+
32+
// Solution using Recursion
33+
/**
34+
* Definition for singly-linked list.
35+
* public class ListNode {
36+
* int val;
37+
* ListNode next;
38+
* ListNode() {}
39+
* ListNode(int val) { this.val = val; }
40+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
41+
* }
42+
*/
43+
class Solution {
44+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
45+
ListNode head = new ListNode(0);
46+
47+
if(list1 == null && list2 == null) return null;
48+
if(list1 == null) return list2;
49+
if(list2 == null) return list1;
50+
51+
if(list1.val > list2.val) {
52+
head = list2;
53+
list2 = list2.next;
54+
} else {
55+
head = list1;
56+
list1 = list1.next;
57+
}
58+
head.next = mergeTwoLists(list1, list2);
59+
return head;
60+
}
61+
}

0 commit comments

Comments
 (0)