Reversing Linked List Leetcode-206
Initial Approach:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev= None
while head:
# print("-",prev,head)
temp_nxt = head.next
head.next = prev
prev = head
head = temp_nxt
# print("=",prev,head)
return prev
I encountered an unexpected issue when I tried to writing this code using tuple assignment/parallel assignment in Python. Let's call this Method-1
prev, head, head.next = head, head.next, prev
I get an error, and the output is not as expected.
AttributeError: 'NoneType' object has no attribute 'next'
^^^^^^^^^
prev, head, head.next = head, head.next, prev
Output: [1,2,3]
- None ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 3, next: None}}}
= ListNode{val: 1, next: ListNode{val: 2, next: None}} ListNode{val: 2, next: None}
- ListNode{val: 1, next: ListNode{val: 2, next: None}} ListNode{val: 2, next: None}
However, when I use the following code, it works fine: Method-2
prev, head.next, head = head, prev, head.next
Output: [1,2,3]
- None ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 3, next: None}}}
= ListNode{val: 1, next: None} ListNode{val: 2, next: ListNode{val: 3, next: None}}
- ListNode{val: 1, next: None} ListNode{val: 2, next: ListNode{val: 3, next: None}}
= ListNode{val: 2, next: ListNode{val: 1, next: None}} ListNode{val: 3, next: None}
- ListNode{val: 2, next: ListNode{val: 1, next: None}} ListNode{val: 3, next: None}
= ListNode{val: 3, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}} None
I'm having trouble understanding why the first approach is causing an issue.
Can someone explain the reason behind this and provide a solution or workaround? Additionally, any insights into how tuple assignment works in this context would be greatly appreciated. Thank you!
head.nextwasNonebefore this started,headwill be assignedNonebeforehead.nextis assigned to. In your "safe" version,headis changed afterhead.nextis assigned to.The difference is that in your version, you assign to cur.next after you've stepped cur to cur.next, so you're actually assigning to the original cur.next.next.This one helped me to understand the issue. Thanks again ;)=assignment as well, so I'm linking the questions for bread crumbs: Python Multiple Assignment Statements In One Line