Search code examples
pythonlinked-listdoubly-linked-list

how to count the nodes in a linked list?


this is my code but im not being able to count the nodes in the list, ive also given the test cases below those test cases should get executed

class LinkedList:
  def __init__(self, a):
    self.head = None
    tail=None
    list=[]
    for x in a:
      if x not in list:
        list+=[x]
      if len(a)!=len(list):
        print("all keys are not unique")
      if len(a)==0:
        print("Array is empty.")
      else:
        for x in a:
          newNode = Node(x, None)
          if (self.head == None):
            self.head = newNode
            tail = newNode
          else:
            tail.next = newNode
            tail = newNode
   
  # Count the number of nodes in the list
  def countNode(self):
    self.head= None
    
    pass # Remove this line

test cases

print("////// Test 01 //////")
a1 = [10, 20, 30, 40]
h1 = LinkedList(a1) # Creates a linked list using the values from the array
# head will refer to the Node that contains the element from a[0]

h1.printList() # This should print: 10,20,30,40
print(h1.countNode()) # This should print: 4

Solution

  • I am assuming your Node looks like this

    class Node:
        def __init__(self, val, next_=None):
            self.element = val
            self.next = next_ # you should use next_ 
    
    
    @property
    def countNode(self):
        temp = self.head
        cnt = 0
        while temp:
            cnt += 1
            temp = temp.next
    
    
    def printList(self):
        temp = self.head
        while temp:
            print(temp.element)  # if Node contains val for value
            temp = temp.next
    

    Going along with your code,

    h1 = LinkedList(a1)
    # for count -> h1.countNode
    # for print -> h1.printList()