Problem 112
Middle of the Linked List
Easy · 10 pts · Linked List, Two Pointers
Problem
You are given a linked list with N nodes. Print the value of its middle node. When N is odd there is exactly one middle node. When N is even there are two, and you should print the second of them. The slow and fast pointer technique finds it in one pass: move one pointer by one node and another by two nodes at a time. When the fast pointer reaches the end, the slow pointer is at the middle.
Input
First line: integer N, the number of nodes. Second line: the N node values from head to tail.
Output
Print the value of the middle node.
Constraints
1 <= N <= 100000; -100000 <= value <= 100000
Example input
5 1 2 3 4 5
Example output
3
Explanation
The list 1 2 3 4 5 has 5 nodes, so the middle is the 3rd node, whose value is 3. For a list of 6 nodes such as 1 2 3 4 5 6, the two middle nodes would be 3 and 4, and the answer would be the second one, 4.