0

I'm trying to understand the solution provided for reversing a linked list. In particular, I don't get why for the very last line we write:

self.head=prev

and not

current=prev

since

current=self.head

I know my reasoning is flawed, that's why I came here for help. Thank you in advance.

class Node: 

    # Constructor to initialize the node object 
    def __init__(self, data): 
        self.data = data 
        self.next = None

class LinkedList: 

    # Function to initialize head 
    def __init__(self): 
        self.head = None
  def reverse(self): 
        prev = None
        current = self.head 
        while(current is not None): 
            next = current.next
            current.next = prev 
            prev = current 
            current = next
        self.head = prev 
  • 2
    Read https://nedbatchelder.com/text/names1.html - rebinding a local variable is not the same as assigning to an attribute. – jonrsharpe Mar 28 '20 at 19:10

1 Answers1

1

= is not equality like in math, it is the assignment/binding operator.

Therefore, after:

current=self.head
current=prev

current will have the value of prev and self.head will have nothing to do with current nor will be modified.

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • So in Python if A=B and B=C, that does not make A=C. A and C have nothing to do with each other. Is that correct? – Victor Gaina Mar 29 '20 at 11:42
  • 1
    @VictorGaina Yes, in Python and in all programming languages where `=` represents assignment. – Acorn Mar 29 '20 at 14:50