#C6513. Reverse a Singly Linked List
Reverse a Singly Linked List
Reverse a Singly Linked List
You are given a singly linked list and your task is to reverse the list. The list is defined using a ListNode
structure. You need to implement an algorithm that reverses the linked list with an optimal memory usage.
The reversal procedure should follow an iterative approach, and the solution must work for various cases including empty lists, lists with a single element, and lists with multiple elements.
Note: The reversal of the linked list can be expressed as:
\(\text{prev} = \text{NULL}, \quad \text{current} = \text{head}\)
and then, for each node, update the pointer as follows:
\(\text{current.next} = \text{prev}\)
Finally, the new head of the list should be returned.
inputFormat
The input is read from standard input (stdin). The first line contains an integer n (n ≥ 0), representing the number of nodes in the linked list. If n > 0, the second line contains n space-separated integers representing the node values in order.
outputFormat
Output the values of the reversed linked list in one line, separated by a single space. If the list is empty, output an empty line.## sample
0