1- public class MergeSortedLinkedLists {
2-
3- }
41class ListNode {
52 int val ;
63 ListNode next ;
7- ListNode (int x ) { val = x ; }
4+ ListNode () {}
5+ ListNode (int val ) { this .val = val ; }
6+ ListNode (int val , ListNode next ) { this .val = val ; this .next = next ; }
87}
98
109public class MergeSortedLinkedLists {
11- // Iteratively merges two sorted linked lists.
1210 public static ListNode mergeTwoLists (ListNode l1 , ListNode l2 ) {
1311 ListNode dummy = new ListNode (-1 );
1412 ListNode current = dummy ;
13+
1514 while (l1 != null && l2 != null ) {
1615 if (l1 .val <= l2 .val ) {
1716 current .next = l1 ;
@@ -22,11 +21,13 @@ public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
2221 }
2322 current = current .next ;
2423 }
24+ // Append remaining nodes
2525 current .next = (l1 != null ) ? l1 : l2 ;
26+
2627 return dummy .next ;
2728 }
2829
29- // Utility to print linked list.
30+ // Utility method to print a linked list
3031 public static void printList (ListNode node ) {
3132 while (node != null ) {
3233 System .out .print (node .val + " " );
@@ -35,6 +36,7 @@ public static void printList(ListNode node) {
3536 System .out .println ();
3637 }
3738
39+ // Example usage
3840 public static void main (String [] args ) {
3941 ListNode head1 = new ListNode (1 );
4042 head1 .next = new ListNode (3 );
@@ -44,7 +46,7 @@ public static void main(String[] args) {
4446 head2 .next = new ListNode (4 );
4547 head2 .next .next = new ListNode (6 );
4648
47- ListNode merged = mergeTwoLists (head1 , head2 );
48- printList (merged ); // Output: 1 2 3 4 5 6
49+ ListNode mergedHead = mergeTwoLists (head1 , head2 );
50+ printList (mergedHead ); // Output: 1 2 3 4 5 6
4951 }
5052}
0 commit comments