Middle of a linked list

A singly linked list can only be walked from the head, and its length is not known in advance. Find its middle node with one pass.

What to build

A program that builds a linked list from the values and prints the values from the middle node to the end.

Requirements

  • Build real nodes (a value and a next reference) and find the middle with a slow and a fast pointer.
  • For an even number of nodes, use the second middle node.

Input

The first line has n. The second line has the n values from head to tail.

Output

The values from the middle node to the tail, separated by spaces.

Constraints

1 ≤ n ≤ 10⁴.

Example

Input:

5
1 2 3 4 5

Output:

3 4 5

Why it works

The fast pointer moves two nodes for each node of the slow pointer. When the fast pointer reaches the end, the slow one has covered half the list, so it stands at the middle after a single pass.

Examples

Example 1 · Input
5
1 2 3 4 5
Expected output
3 4 5
Example 2 · Input
6
1 2 3 4 5 6
Expected output
4 5 6

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Move a slow pointer one node and a fast pointer two nodes at a time.

Hint 2

When fast cannot move any more, slow is at the middle.

Hint 3

With an even number of nodes, the answer is the second of the two middle nodes.

Solution

Show one correct solution (try it yourself first)
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next


n = int(input())
values = input().split()
head = None
for v in reversed(values):
    head = Node(v, head)
slow = fast = head
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
out = []
while slow:
    out.append(slow.value)
    slow = slow.next
print(*out)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Linked list patterns →