All problems

Problem 111

Reverse Linked List

Easy · 10 pts · Linked List, Recursion

Problem

You are given a singly linked list, where each node stores a value and a pointer to the next node. Reverse the list so that the last node becomes the head and every pointer points the other way, then print the values from the new head to the new tail. An empty list stays empty. Walk through the list once with three pointers (previous, current, next): at each node, save its next node, point it back at the previous node, and move all pointers one step forward.

Input

First line: integer N, the number of nodes. Second line: the N node values from head to tail.

Output

Print the node values of the resulting list from head to tail, space-separated, or EMPTY if it has no nodes.

Constraints

0 <= N <= 5000; -5000 <= value <= 5000

Example input

5
1 2 3 4 5

Example output

5 4 3 2 1

Explanation

The list 1 → 2 → 3 → 4 → 5 is reversed into 5 → 4 → 3 → 2 → 1, so the output is 5 4 3 2 1.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Count Smaller Numbers After Self Next: Middle of the Linked List