@@ -32,4 +32,71 @@ Return _the head of the merged linked list_.
3232
3333* The number of nodes in both lists is in the range ` [0, 50] ` .
3434* ` -100 <= Node.val <= 100 `
35- * Both ` list1 ` and ` list2 ` are sorted in ** non-decreasing** order.
35+ * Both ` list1 ` and ` list2 ` are sorted in ** non-decreasing** order.
36+
37+ To solve the Merge Two Sorted Lists problem in Java with a ` Solution ` class, we'll implement a recursive approach. Here are the steps:
38+
39+ 1 . Define a ` ListNode ` class to represent a node in the linked list.
40+ 2 . Define a ` Solution ` class with a method named ` mergeTwoLists ` that takes two linked lists ` l1 ` and ` l2 ` as input and returns a merged sorted list.
41+ 3 . The base case for the recursion is when either ` l1 ` or ` l2 ` is null. In this case, return the non-null list because it's already sorted.
42+ 4 . Compare the values of the heads of ` l1 ` and ` l2 ` . Let ` head ` be the smaller value of the two heads.
43+ 5 . Recursively call ` mergeTwoLists ` with the next node of the smaller head and the other list that remained unchanged.
44+ 6 . Update the ` next ` pointer of the smaller head to point to the result of the recursive call.
45+ 7 . Return the smaller head, which is the merged sorted list.
46+
47+ Here's the implementation:
48+
49+ ``` java
50+ public class Solution {
51+ static class ListNode {
52+ int val;
53+ ListNode next;
54+
55+ ListNode (int val ) {
56+ this . val = val;
57+ }
58+ }
59+
60+ public ListNode mergeTwoLists (ListNode l1 , ListNode l2 ) {
61+ if (l1 == null ) {
62+ return l2;
63+ }
64+ if (l2 == null ) {
65+ return l1;
66+ }
67+
68+ ListNode head;
69+ if (l1. val < l2. val) {
70+ head = l1;
71+ head. next = mergeTwoLists(l1. next, l2);
72+ } else {
73+ head = l2;
74+ head. next = mergeTwoLists(l1, l2. next);
75+ }
76+
77+ return head;
78+ }
79+
80+ public static void main (String [] args ) {
81+ Solution solution = new Solution ();
82+
83+ // Test cases
84+ ListNode l1 = new ListNode (1 );
85+ l1. next = new ListNode (2 );
86+ l1. next. next = new ListNode (4 );
87+
88+ ListNode l2 = new ListNode (1 );
89+ l2. next = new ListNode (3 );
90+ l2. next. next = new ListNode (4 );
91+
92+ ListNode mergedList = solution. mergeTwoLists(l1, l2);
93+ while (mergedList != null ) {
94+ System . out. print(mergedList. val + " " );
95+ mergedList = mergedList. next;
96+ }
97+ System . out. println(); // newline
98+ }
99+ }
100+ ```
101+
102+ This implementation provides a solution to the Merge Two Sorted Lists problem in Java using a recursive approach.
0 commit comments