Sina Hwz Sina Hwz - 5 months ago 12
Python Question

Linked-list Data Structure understanding

I have a little difficulty in understanding one thing in the structure of the Linked-lists.
Basically nodes of a linked list are created using the following class, and the next reference is obtained by the method getNext():
I have omitted other methods as not relevant to my problem.

class Node:
def __init__(self,initdata): = initdata = None

def getNext(self):

Now when creating a linkedlist and trying to find the size of the linked-list:

class UnorderedList:
def __init__(self):
self.head = None

def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext() <-----

return count

I do not understand the line shown with an arrow. I know the logic that it tries to traverse to the next node, but getNext() is the method of the "NodeClass". how is it (getNext() method) being used by an object (i.e. current) which is not a NodeClass object? and actually it is an object of the "UnorderedList" class.


current is basically an instance of UnOrderedList in which each element is Node object. Hence the methods that are applied on Nodes can be applied on each element of current. Nodes are added to UnOrderedList using the add method.

def add(self,item):
    temp = Node(item)
    self.head = temp