Middle of the Linked List
Find the value stored in the middle node of a singly-linked list in a single pass.
Given the head of a singly-linked list, return the value stored in the middle node of the list.
If the list has an even number of nodes, there are two middle nodes -- in that case, return the value of the second of the two middle nodes.
Example 1
Input: head = [1,2,3,4,5]
Output: 3
Explanation: The list has an odd length, so there's a single middle node with value 3.
Example 2
Input: head = [1,2,3,4,5,6]
Output: 4
Explanation: The list has an even length, so there are two middle nodes (3 and 4) -- return the second one.
Example 3
Input: head = [1]
Output: 1
Constraints
- The number of nodes in the list is in the range [1, 100].
- -1000 <= Node.val <= 1000
Follow-up
Can you find the middle in a single pass, without first computing the length of the list?
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
No test cases yet.