1
class ListNode:
    def __init__(self, value = 0, next = None): 
        self.value = value
        self.next = next
        
    def print(self):
        print(self.value)
        if self.next is not None:
            self.next.print()

A = ListNode(1, ListNode(2, ListNode(3)))
B = ListNode(4, ListNode(5, ListNode(6)))

A.next, A = B, A

A.print()

Based on the last example here https://docs.python.org/3/reference/expressions.html#evaluation-order, shouldn't it be 1->2->3 instead of 1->4->5->6?

  • 1
    The assignment `A.next, A = B, A` is the same as `A.next = B`. This means that chain `A.next` used to point to -> `ListNode(2, ListNode(3))`, now points to `B`, `ListNode(4, ListNode(5, ListNode(6)))`. There is no longer a link between `1` and `2`. In other words `A.next` is not the last element in the list, it is the second element in the list. – Mark Jul 17 '22 at 03:26
  • [https://docs.python.org/3/reference/simple_stmts.html#assignment-statements](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements) ... `(A.next, A) = (B, A)` – wwii Jul 17 '22 at 03:29
  • [https://stackoverflow.com/a/21990952/2823755](https://stackoverflow.com/a/21990952/2823755) – wwii Jul 17 '22 at 03:34
  • I don't understand what your reasoning is to expect 1->2->3. – trincot Jul 17 '22 at 10:04

1 Answers1

0

You are getting this because of this line

A.next, A = B, A

With the part A.next = B, the next pointer of A is already pointing to B. So, when you are assigning A with A again (A = A), A.next is not pointing to 2 anymore but rather to 4.

Shahad Mahmud
  • 410
  • 1
  • 4
  • 14