File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments