Middle of the Linked List
Easy · linked list
You are given the head of a singly linked list. Return the node in the middle of the list, which also gives you the rest of the list from that node to the end.
If the list has an odd number of nodes there is exactly one middle node. If it has an even number of nodes there are two, and you must return the second one.
The nodes you receive are ListNode objects with a val and a next. Your answer is shown as the list that starts at the node you return.
Examples
Example 1
Input: head = [4, 8, 15, 16, 23]
Output: [15, 16, 23]
Five nodes, so the middle is the 3rd one, 15. The list from there is 15, 16, 23.
Example 2
Input: head = [1, 2, 3, 4]
Output: [3, 4]
Four nodes have two middles, 2 and 3. The second one, 3, is returned.
Example 3
Input: head = [9]
Output: [9]
Constraints
- 1 <= number of nodes <= 2000
- -10^4 <= Node.val <= 10^4