Middle of the Linked List — Fast & Slow Pointers
Find the central item of a chain, preferring the later item if there is a tie in the middle, and return everything from there on.
Fast & Slow Pointers · Easy
The problem
The carts of a baggage train are coupled one behind the other, and you hold the front cart (head). Return the cart at the centre of the train. If the train has two centre carts, return the second of them.
The story
A baggage train of 1 to 600 carts is coupled one behind another at an airport, and you're at the front cart. The ground crew wants to hang the transfer sign on the centre cart. Find it; if there are two centre carts, pick the second one. The cart you hand back comes with everything coupled behind it.
What to return
- Return the middle node. The checker reads the list from that node to the end, so the answer is the middle value followed by everything after it.
- For an even number of nodes the middle is the second of the two central nodes.
Constraints
- 1 <= length of head <= 600
- -50 <= node value <= 50
- Your code may run at most 3,612 counted steps on the largest case.
Example
- Input
head = 7→3→9→4→8- Output
9→4→8