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,
prev
andcurrent
. Theprev
pointer is initialized tonull
because the new tail (originally the first node) should point tonull
after reversal. Thecurrent
pointer starts at the head of the list.Iteration: Traverse the list with the
current
pointer. 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
next
pointer to point to theprev
node.Move pointers forward: Update
prev
to be the current node and movecurrent
to the next node in the original list (which was stored earlier).
Termination: Once
current
becomesnull
, theprev
pointer 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
prev
pointer starts asnull
because the first node of the original list will become the last node in the reversed list, pointing tonull
. Thecurrent
pointer 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
prev
to the current node andcurrent
to the next node (nextTemp
).
Termination: When
current
becomesnull
,prev
will be pointing to the last node of the original list, which is now the head of the reversed list. We returnprev
as the new head.
No comments:
Post a Comment