This code is blowing my mind

I understand what the last three lines are supposed to do(update the pointers of the swapped nodes) I just don’t follow how. Maybe i need a break. I’m currently wired on coffee listening to aphex twin. S950tx16wasr10 [163.97] - YouTube

https://www.codecademy.com/paths/computer-science/tracks/cspath-cs-102/modules/linked-lists/articles/swapping-elements-in-a-linked-list-python

def swap_nodes(linked_list, val1, val2):
    node1 = linked_list.head_node
    node2 = linked_list.head_node
    node1_prev = None
    node2_prev = None

    while node1 != None:
        if node1.get_value() == val1:
            break
        node1_prev = node1
        node1 = node1.get_next_node()

    while node2!= None:
        if node2.get_value() == val2:
            break
        node2_prev = node2
        node2 = node2.get_next_node()

    if node1_prev == None:
        linked_list.head_node = node2
    else:
        node1_prev.set_next_node(node2)

    if node2_prev == None:
        linked_list.head_node = node1
    else:
        node2_prev.set_next_node(node1)

    temp = node1.get_next_node()
    node1.set_next_node(node2.get_next_node())
    node2.set_next_node(temp)```

my brain is going to explode XD

Please post a link to the exercise page for more context.

https://www.codecademy.com/paths/computer-science/tracks/cspath-cs-102/modules/linked-lists/articles/swapping-elements-in-a-linked-list-python

1 Like

There are few moving parts, to be sure. If you have a white board, it might be helpful to sketch it out (or on a fresh sheet of paper).

As for the last swap, if we don’t update the pointers we end up with circular references and the linked list is corrupted.

The author uses the conventional array element swap…

temp = a
a = b
b = temp

Python lets us omit the temp variable…

a, b = b, a

effectively performs the swap, but that is beside the point.

1 Like

Thanks. Drawing it helped me understand !!

1 Like