#C14370. Reverse a Singly Linked List
Reverse a Singly Linked List
Reverse a Singly Linked List
You are given a singly linked list. Your task is to reverse the linked list and output the reversed list.
The linked list is defined using a basic node structure. In this problem, you will implement the reverse operation which reverses the pointers of the linked list.
Note: The reversal algorithm should be implemented using the iterative approach without using any additional data structure for storing nodes.
For example, if the input linked list is \(1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5\), then the output will be \(5 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 1\).
inputFormat
The input is provided via stdin
in the following format:
- The first line contains an integer \(n\), representing the number of nodes in the linked list. \(n\) can be 0, which indicates an empty list.
- If \(n > 0\), the second line contains \(n\) space-separated integers, representing the node values in the order of the linked list.
outputFormat
Output the node values of the reversed linked list in one line via stdout
, separated by a single space. If the list is empty, output nothing.
5
1 2 3 4 5
5 4 3 2 1