Tuple unpacking in Py (when reversing linked list)

whitehousechef·2025년 3월 4일

Refer to https://velog.io/@whitehousechef/Leetcode-2130.-Maximum-Twin-Sum-of-a-Linked-List-tuple-unpacking for full question

VERY IMPT tuple unpacking

        while fast and fast.next:
            fast=fast.next.next
            slow.next, prev, slow = prev, slow, slow.next

The order of tuple unpacking matters. The expressions on the right are all evaluated first before assiging them on those left variables. This is the correct order. You first change the next pointer of the current slow node to point to the previous node. Then you shift the prev pointer forward to the current slow node, and then shift the slow pointer forward to the next node.

If we had

slow, prev, slow.next = slow.next, slow, prev

The problem here is that you're changing slow before you change slow.next. This means that when you try to set slow.next to prev, you're now working with the new slow (which is the old slow.next), rather than the original slow. This will corrupt your linked list.

0개의 댓글