Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
for peoples who are confused why head = prev ??

Faraz

May 9, 2024

head = prev is used to update the head of the linked list when p === 1, i.e., when we are reversing the sublist starting from the very beginning of the original list.

When p === 1, it means that the sublist we are reversing starts from the very beginning of the original linked list. In this case, after reversing, the head of the sublist becomes the new head of the entire list. Therefore, prev will hold the reference to the new head of the list after the reversal.

When p !== 1, last_node_of_first_part will hold the reference to the node just before the sublist we are reversing. In this case, we will update the next pointer of last_node_of_first_part to point to prev, which is the new head of the reversed sublist. So, in the case where p === 1, we update head to prev because prev now represents the new head of the list after the reversal.

1

0

Comments
Comments