- LeetCode
- 876 que
- LeetCode 75
MY LEETCODE ID – https://leetcode.com/oshoup521/
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.Example 2:

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.Constraints:
- The number of nodes in the list is in the range
[1, 100]. 1 <= Node.val <= 100
Solution: (In JAVA)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
// Edge case: if the linked list is empty or has only one node, return the head
if (head == null || head.next == null) {
return head;
}
// Initialize two pointers, slow and fast, to the head of the linked list
ListNode slow = head;
ListNode fast = head;
// Iterate through the linked list using the fast pointer
while (fast != null && fast.next != null) {
// Move the slow pointer one node at a time
slow = slow.next;
// Move the fast pointer two nodes at a time
fast = fast.next.next;
}
// When the fast pointer reaches the end of the linked list, the slow pointer will be at the middle node
return slow;
}
}
I hope this solution may help you understanding this problem for further more solution related to LeetCode and GeeksForGeeks stay connected.
-OSHO UPADHYAY



