Reputation: 47
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
Upvotes: 0
Views: 58
Reputation: 26176
=
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.
Upvotes: 1