Reverse a Singly Linked List
Explore methods to reverse a singly linked list by implementing iterative and recursive approaches. Understand how to manipulate pointers to change node order, and evaluate solutions by their time and space complexity for effective problem-solving.
Statement
Given the head of a singly linked list, reverse the linked list and return its new or updated head.
Example
Consider the following linked list:
Return the pointer to the reversed linked list as shown in the figure:
Sample input
[7, 14, 21, 28]
Expected output
[28, 21, 14, 7]
Try it yourself #
Solution 1
If the linked list only contains 0 or 1 node, then the current list can be returned as it is. If there are two or more nodes, then the iterative solution starts with two node pointers:
- First pointer: points to the head of the input linked list.
- Second pointer: It points to the head’s next node.
We then set the next of the first pointer to NULL. It becomes the last node in the new reversed linked list. The first pointer always points to the ...