So I'm following this linked list, and it is an ordered linked list. For reference here is the code:
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class OrderedList:
def __init__(self):
self.head = None
def add(self,item):
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getData() > item:
stop = True
else:
previous = current
current = current.getNext()
temp = Node(item)
if previous == None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)
def isEmpty(self):
return self.head == None
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
mylist = OrderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
print(mylist.size())
As you can see, when calling mylist.size()
, it will return a size of 6 because there are 6 things that were added. But in the add method, specifically the lines:
if previous == None:
temp.setNext(self.head)
self.head = temp
If I were to change self.head = temp
to current = temp
it would return a size of 0. Which means that the rest of the numbers didn't get referenced. But why is this the case, I thought that since we defined current = self.head
earlier, changing self.head = temp
to current = temp
would yield the same results?