Given the head of a singly linked list, reverse the list, and return the reversed list.
[0, 5000].-5000 <= Node.val <= 5000Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
The iterative approach involves using a loop to reverse the pointers of the linked list's nodes one by one. By starting from the head, we can keep track of the previous node and progressively change the current node's next pointer to point to this previous node. We move through the list, effectively flipping all the pointers, until the entire list is reversed.
prev (set to null), curr (set to head), and next (to store the curr.next node temporarily).curr.next in next to save the rest of the list.curr node to point to prev.prev and curr one step forward.curr becomes null.prev node.n is the number of elements in the list.The recursive approach involves diving deeper into the list until we reach the end and starting the reversal from there. As each recursive call returns, we reverse the pointers at that level. This way, the pointers are adjusted in a postfix manner.
head is null or head.next is null, return head. This means we found the new head of the reversed list.head.next.next to head and set head.next to null.n frames, one for each node in the list.