0

Recently I encountered the following multiple assignment, and have no idea how it swaps two nodes. I want to swap two nodes in a linked list. The code is :

head, head.next = head.next, head

as seen on https://leetcode.com/problems/swap-nodes-in-pairs/discuss/171788/Python-or-Dummynode

Can someone break down the steps and tell me how that code swaps head and head.next? It's very confusing to me.

Corp. and Ltd.
  • 401
  • 2
  • 5
  • 17
  • first, it makes a copy of `head.next` and head which are on the right side the `=`. then assigns them to variables on the left side of `=` respectively. – prhmma Dec 27 '19 at 03:32
  • This question contains a detailed explanation of this in general https://stackoverflow.com/questions/24844487/swap-2-values-of-2-variables-without-using-a-third-variable-python In your context it works the same way. – mrEvgenX Dec 27 '19 at 03:33
  • @mrEvgenX I am aware of how multiple assignments are used in variables, but I do not quite understand how they are used in linked lists. After all, linked lists have to be linked. I am wondering how are they still linked after the multiple assignment. – Corp. and Ltd. Dec 27 '19 at 03:35
  • @prhmma it does not make copies. – juanpa.arrivillaga Dec 27 '19 at 04:13

1 Answers1

1

I struggled with this a little bit and came up with the explanation.

head, head.next = head.next, head

is equivalent to the code

bob = head.next
alice = head
head = bob
head.next = alice

In other words, it takes a snapshot (or evaluates) of head.next and head (represented by bob and alice respectively), and allocates them to head and head.next

Expanding out the multiple assignment helped me to understand what it does.

Corp. and Ltd.
  • 401
  • 2
  • 5
  • 17