Can anyone explain why the position of this line head=head.next
must be right after curr=head
and not any further down? Initially, I was putting head=head.next
in the last line of the while loop but was getting only the last node. Eg. If the input was [1,2,3]
, I would get [1]
using the second block of code and [3,2,1]
with the first.
Correct:
def reverseListIterative(head: ListNode):
prev = None
while head:
curr = head
head = head.next
curr.next = prev
prev = curr
return prev
Wrong:
def reverseListIterative(head: ListNode):
prev = None
while head:
curr = head
curr.next = prev
prev = curr
head = head.next
return prev
You could figure this out by tracking the content of each variable through the code flow (you don't even need to run it):
Let's say we start with the list 1 -> 2 -> 3
prev curr head head.next curr.next
---- ---- ---- --------- ---------
prev = None None - 1 2 -
while head:
curr = head None 1 1 2 2
curr.next = prev None 1 1 None None ***
prev = curr 1 1 1 None None
head = head.next 1 1 None - None
return prev
When you assign prev (None) to curr.next, you lose the connection from head.next because head is also pointing to node #1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.