meta data for this page
  •  

Middle of the Linked List

Leetcode


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:

assets.leetcode.com_uploads_2021_07_23_lc-midlist1.jpg

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

Solution 1

Solution 1

public ListNode middleNode(ListNode head) {
  if (head == null || head.next == null) return head;
 
  ListNode slow = head;
  ListNode fast = slow.next;
 
  while (fast != null) {
    slow = slow.next;
    if (fast.next == null) break;
    fast = fast.next.next;
  }
 
  return slow;
}