Problem 206478 · easy · Level 02 Linear Data Structures

Find the Middle Carriage

linked lists · fast & slow pointers

Because a linked list has no length field and no indices, even "go to the middle" needs a traversal. One classic approach uses two pointers moving at different speeds.

A train is stored as a singly linked list of carriages, head first, and the guard rides in the middle carriage. An odd number of carriages has one middle; an even number has two, and the guard takes the second of them, the one nearer the back. Return that carriage node itself, not its value; the tests convert the rest of the list from that node onward.

Examples

Input:  5 -> 8 -> 2 -> 6 -> 1
Output: the node 2 (so the list from it reads 2 -> 6 -> 1)
Input:  4 -> 9 -> 3 -> 7 -> 1 -> 8
Output: the node 7 (the second of the two middle nodes, 3 and 7)

Constraints

  • 1 <= number of nodes <= 1000

Goals

  • Find the length of a linked list by traversal
  • Apply the fast and slow pointer technique to locate the middle in one pass
Starting Python…