Saketh
Saketh

Reputation: 21

Tuple unpacking issue in reversing a linked list using tuple unpacking in Python

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!

Upvotes: 1

Views: 56

Answers (0)

Related Questions