Skip to content

Commit 71a0db7

Browse files
Merge pull request #118 from itsAkshat-jain/patch-2
Merge_Two_Sorted_List
2 parents 8eba900 + e602e65 commit 71a0db7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
Code for merge two sorted list and make a single sorted list
2+
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* public class ListNode {
7+
* int val;
8+
* ListNode next;
9+
* ListNode() {}
10+
* ListNode(int val) { this.val = val; }
11+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
12+
* }
13+
*/
14+
15+
class Solution {
16+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
17+
18+
// The case where both lists are empty
19+
if(list1 == null && list2 == null){
20+
return null;
21+
// The 2 cases that describe one of the other is empty
22+
}else if(list1 == null && list2 != null){
23+
return list2;
24+
} else if (list1 != null && list2 == null) {
25+
return list1;
26+
// The case that describes the beginning of the sorting
27+
// ie, list1's first value is smaller or equal to list2
28+
}else if(list1.val <= list2.val) {
29+
list1.next = mergeTwoLists(list1.next, list2);
30+
return list1;
31+
}else {
32+
list2.next = mergeTwoLists(list1, list2.next);
33+
return list2;
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)