11package com .thealgorithms .datastructures .lists ;
22
3- // Definition for singly-linked list node
4- public class ListNode {
5- public int val ; // Value stored in the node
6- public ListNode next ; // Pointer to the next node
7-
8- public ListNode (int val ) {
9- this .val = val ;
10- this .next = null ;
3+ /**
4+ * Class to find the middle node of a singly-linked list.
5+ */
6+ public class MiddleOfLinkedList {
7+
8+ /**
9+ * Definition for singly-linked list node.
10+ * Package-private class so it can be used internally.
11+ */
12+ static class ListNode {
13+ int val ; // Value stored in the node
14+ ListNode next ; // Pointer to the next node
15+
16+ /**
17+ * Constructor to initialize a node with a value.
18+ *
19+ * @param val Value to store in the node.
20+ */
21+ ListNode (int val ) {
22+ this .val = val ;
23+ this .next = null ;
24+ }
1125 }
12- }
1326
14- public class MiddleOfLinkedList {
27+ /**
28+ * Finds the middle node of a singly linked list.
29+ * If there are two middle nodes, returns the second one.
30+ *
31+ * @param head Head node of the linked list.
32+ * @return Middle node of the list.
33+ */
1534 public ListNode middleNode (ListNode head ) {
1635 if (head == null ) {
1736 return head ;
1837 }
1938
20- ListNode slow = head ;
21- ListNode fast = head ;
39+ ListNode slow = head ; // moves one step at a time
40+ ListNode fast = head ; // moves two steps at a time
2241
2342 while (fast != null && fast .next != null ) {
24- slow = slow .next ;
25- fast = fast .next .next ;
43+ slow = slow .next ; // move slow by one node
44+ fast = fast .next .next ; // move fast by two nodes
2645 }
2746
2847 return slow ;
2948 }
3049
50+ /**
51+ * Helper method to create a linked list from an array.
52+ *
53+ * @param values Array of integer values.
54+ * @return Head node of the created linked list.
55+ */
3156 public static ListNode createList (int [] values ) {
3257 if (values .length == 0 ) {
3358 return null ;
@@ -44,10 +69,15 @@ public static ListNode createList(int[] values) {
4469 return head ;
4570 }
4671
72+ /**
73+ * Helper method to print the linked list starting from any node.
74+ *
75+ * @param node Starting node to print from.
76+ */
4777 public static void printList (ListNode node ) {
4878 while (node != null ) {
49- System .out .print (node .val + " " );
50- node = node .next ;
79+ System .out .print (node .val + " " ); // print current node value
80+ node = node .next ; // move to next node
5181 }
5282 System .out .println ();
5383 }
0 commit comments