Need help with Python references


  • 0
    A

    Hello

    I was writing code to reverse a doubly linked list and managed to solve it correctly but now I’m confused what python is actually doing here. Here is the code:

    def reverse(self):
            print(self.head)
            current = self.head
            self.head, self.tail = self.tail, self.head
            while current:
                print(self.head)
                current.link, current.prev, current= current.prev, current.link, current.link
            print(self.head)
            return self
    

    So I set current to the head and then I swapped the head and tail of the linked list. Now this is where I’m confused. The two print statements of self.head are never the same. Within the for loop it still shows the tail but right when it leaves the loop it automatically turns into the correct linked list. Here’s is the output of an example.

    0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> None
    9 -> None
    9 -> None
    9 -> None
    9 -> None
    9 -> None
    9 -> None
    9 -> None
    9 -> None
    9 -> None
    9 -> None
    9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0 -> None

    So now I am just curious how Python is doing this. So what is current referencing after I swapped the head and the tail and how does it manage to give the right answer?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.