Skip to content

Commit ea041c3

Browse files
authored
Create MiddleOfLinkedList.java
1 parent e6cb96f commit ea041c3

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// 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
5+
6+
// Constructor to initialize node with a value
7+
ListNode(int val) {
8+
this.val = val;
9+
this.next = null;
10+
}
11+
}
12+
13+
public class Solution {
14+
15+
/**
16+
* Finds the middle node of a singly linked list.
17+
* If there are two middle nodes, returns the second one.
18+
*/
19+
public ListNode middleNode(ListNode head) {
20+
// If the list is empty, just return null
21+
if (head == null) return head;
22+
23+
// Initialize two pointers: slow and fast
24+
ListNode slow = head; // moves one step at a time
25+
ListNode fast = head; // moves two steps at a time
26+
27+
// Traverse the list
28+
// When 'fast' reaches the end, 'slow' will be at the middle
29+
while (fast != null && fast.next != null) {
30+
slow = slow.next; // move slow by one node
31+
fast = fast.next.next; // move fast by two nodes
32+
}
33+
34+
// When loop ends, slow is pointing at the middle node
35+
return slow;
36+
}
37+
38+
/**
39+
* Helper method to create a linked list from an array.
40+
* Example: [1,2,3,4] → 1 → 2 → 3 → 4
41+
*/
42+
public static ListNode createList(int[] values) {
43+
// If the array is empty, return null
44+
if (values.length == 0) return null;
45+
46+
// Create the head node
47+
ListNode head = new ListNode(values[0]);
48+
ListNode current = head;
49+
50+
// Loop through the rest of the array to build the list
51+
for (int i = 1; i < values.length; i++) {
52+
current.next = new ListNode(values[i]); // create next node
53+
current = current.next; // move pointer forward
54+
}
55+
56+
return head; // return the head of the linked list
57+
}
58+
59+
/**
60+
* Helper method to print the linked list starting from any node.
61+
* Example: prints "3 4 5"
62+
*/
63+
public static void printList(ListNode node) {
64+
while (node != null) {
65+
System.out.print(node.val + " "); // print current node value
66+
node = node.next; // move to next node
67+
}
68+
System.out.println(); // print newline after list
69+
}
70+
71+
public static void main(String[] args) {
72+
Solution sol = new Solution();
73+
74+
// Input array for the linked list
75+
int[] values = {1, 2, 3, 4, 5}; // Odd-length list
76+
77+
// Create linked list from array
78+
ListNode head = createList(values);
79+
80+
// Find middle node
81+
ListNode middle = sol.middleNode(head);
82+
83+
// Print all nodes from middle to end
84+
System.out.print("Middle node and following nodes: ");
85+
printList(middle); // Expected output: 3 4 5
86+
}
87+
}

0 commit comments

Comments
 (0)