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.

4
  • 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. Commented Dec 27, 2019 at 3:32
  • This question contains a detailed explanation of this in general stackoverflow.com/questions/24844487/… In your context it works the same way. Commented Dec 27, 2019 at 3: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. Commented Dec 27, 2019 at 3:35
  • @prhmma it does not make copies. Commented Dec 27, 2019 at 4:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.