0

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?

IHaveAQuestion
  • 143
  • 2
  • 12

1 Answers1

1
current = self.head
current = temp

The first line above will make current refer to whatever self.head refers to. The second line makes current refer to temp, but it does not also make self.head refer to temp.

You can think of current as a reference to some underlying object (that also happens to be referenced by self.head). Reassigning current to temp does not change what self.head refers to.

This can be a common confusion when working with Python and there is a lot more info on the way objects and names are dealt with. See e.g. Python variable reference assignment

Alex
  • 947
  • 6
  • 16