1+ package com .thealgorithms .datastructures .lists ;
2+
13// Definition for singly-linked list node
2- class ListNode {
3- int val ; // Value stored in the node
4- ListNode next ; // Pointer to the next node
4+ public class ListNode {
5+ public int val ; // Value stored in the node
6+ public ListNode next ; // Pointer to the next node
57
6- /**
7- * Constructor to initialize a node with a value.
8- *
9- * @param val Value to store in the node.
10- */
11- ListNode (int val ) {
8+ public ListNode (int val ) {
129 this .val = val ;
1310 this .next = null ;
1411 }
1512}
1613
1714public class MiddleOfLinkedList {
18-
19- /**
20- * Finds the middle node of a singly linked list.
21- * If there are two middle nodes, returns the second one.
22- *
23- * @param head Head node of the linked list.
24- * @return Middle node of the list.
25- */
2615 public ListNode middleNode (ListNode head ) {
2716 if (head == null ) {
2817 return head ;
2918 }
3019
31- ListNode slow = head ; // moves one step at a time
32- ListNode fast = head ; // moves two steps at a time
20+ ListNode slow = head ;
21+ ListNode fast = head ;
3322
3423 while (fast != null && fast .next != null ) {
35- slow = slow .next ; // move slow by one node
36- fast = fast .next .next ; // move fast by two nodes
24+ slow = slow .next ;
25+ fast = fast .next .next ;
3726 }
3827
3928 return slow ;
4029 }
4130
42- /**
43- * Helper method to create a linked list from an array.
44- *
45- * @param values Array of integer values.
46- * @return Head node of the created linked list.
47- */
4831 public static ListNode createList (int [] values ) {
4932 if (values .length == 0 ) {
5033 return null ;
@@ -54,22 +37,17 @@ public static ListNode createList(int[] values) {
5437 ListNode current = head ;
5538
5639 for (int i = 1 ; i < values .length ; i ++) {
57- current .next = new ListNode (values [i ]); // create next node
58- current = current .next ; // move pointer forward
40+ current .next = new ListNode (values [i ]);
41+ current = current .next ;
5942 }
6043
6144 return head ;
6245 }
6346
64- /**
65- * Helper method to print the linked list starting from any node.
66- *
67- * @param node Starting node to print from.
68- */
6947 public static void printList (ListNode node ) {
7048 while (node != null ) {
71- System .out .print (node .val + " " ); // print current node value
72- node = node .next ; // move to next node
49+ System .out .print (node .val + " " );
50+ node = node .next ;
7351 }
7452 System .out .println ();
7553 }
0 commit comments