In each iteration of the loop, we first store a reference to the next attribute of curr in the next_node variable. This is done to ensure that we don’t lose the reference to the next node in the original linked list when we modify the next attribute of curr.
We then set the next attribute of curr to prev, effectively reversing the direction of the next pointer of curr.swap_elements
We update prev to be curr, so that it points to the current node in the reversed linked list.
We update curr to be next_node, so that it points to the next node in the original linked list.
The loop terminates when curr becomes None. This happens when we have processed all nodes in the original linked list.
At this point, prev points to the last node in the original linked list, which is now the first node in the reversed linked list. Therefore, we return prev.
Had missed adding variable declaration, adding let increased the memory and reduced the runtime.
Add edge case if head is null return head or return null.
'''#gyan_pelo to reverse a linked list change the pointer or the next to the previous elementhave two elements at a time in the #maintaince_phase scope and change the next pointer to previoususe only a temporary variable if required, don't store the values in another array or linked list or stack because than it will not be #in_place '''
/**gyan pelo:To reverse the linked list the pointers have to be flipped. Store the current node value then override it. Also last node needs to point to null so at starting of loop handle that. Previous should have the updated linked list.**/class Node { value; next; constructor(value, next) { this.value = value; this.next = next; }}function reverseLinkedList(head) { previous = null; current = head; while (current != null) { next_value = current.next; current.next = previous; [previous, current] = [current, next_value] } return previous;}var head = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5))))) result = reverse_linked_list(head);