Approach
The approach involves iterating through the linked list while reversing the pointers of each node. Here’s a step-by-step breakdown:
Initialization: Start with two pointers,
prevandcurrent. Theprevpointer is initialized tonullbecause the new tail (originally the first node) should point tonullafter reversal. Thecurrentpointer starts at the head of the list.Iteration: Traverse the list with the
currentpointer. For each node:Store the next node: Temporarily store the next node of the current node to avoid losing the reference when we change the current node's pointer.
Reverse the pointer: Set the current node's
nextpointer to point to theprevnode.Move pointers forward: Update
prevto be the current node and movecurrentto the next node in the original list (which was stored earlier).
Termination: Once
currentbecomesnull, theprevpointer will be at the new head of the reversed list. Returnprev.
This approach efficiently reverses the list in a single pass through the nodes with constant space complexity, making it optimal.
Solution Code
class ListNode { constructor(val = 0, next = null) { this.val = val; this.next = next; } } function reverseList(head) { let prev = null; let current = head; while (current !== null) { const nextTemp = current.next; current.next = prev; prev = current; current = nextTemp; } return prev; } // Debug your code below let head = new ListNode(1, new ListNode(2)); let reversedHead = reverseList(head); console.log(reversedHead.val); console.log(reversedHead.next.val);
Explanation
Initialization: The
prevpointer starts asnullbecause the first node of the original list will become the last node in the reversed list, pointing tonull. Thecurrentpointer starts at the head of the list.Loop Through List: For each node, we:
Store the next node (
nextTemp) to remember the rest of the list.Reverse the current node's pointer to point to
prev.Move
prevto the current node andcurrentto the next node (nextTemp).
Termination: When
currentbecomesnull,prevwill be pointing to the last node of the original list, which is now the head of the reversed list. We returnprevas the new head.
No comments:
Post a Comment