Arihant Jain
Arihant Jain

Reputation: 11

How to count number of nodes of LinkedList using python

Given a linked list containing brand names of biscuits sold by a retail store, write a python function which finds and returns the total number of biscuit brands.

class Node:
    def __init__(self,data):
        self.__data=data
        self.__next=None

    def get_data(self):
        return self.__data

    def set_data(self,data):
        self.__data=data

    def get_next(self):
        return self.__next

    def set_next(self,next_node):
        self.__next=next_node

class LinkedList:
    def __init__(self):
        self.__head=None
        self.__tail=None

    def get_head(self):
        return self.__head

    def get_tail(self):
        return self.__tail

    def add(self,data):
        new_node=Node(data)
        if(self.__head is None):
                self.__head=self.__tail=new_node
        else:
                self.__tail.set_next(new_node)
                self.__tail=new_node

def count_nodes(biscuit_list):
    count=0
 #PLEASE HELP ME IN THIS CODE TO GET SUITABLE OUTPUT....
    temp = Node.get_data(biscuit_list.get_head()) 
    while(temp is not None):
        count += 1
        temp = Node(temp).get_next()
    return count


biscuit_list=LinkedList()
biscuit_list.add("Goodday")
biscuit_list.add("Bourbon")
biscuit_list.add("Hide&Seek")
biscuit_list.add("Nutrichoice")

print(count_nodes(biscuit_list))

The output is 1, but that is wrong. The correct output is 4.

Upvotes: 0

Views: 3196

Answers (2)

jbndlr
jbndlr

Reputation: 5210

Your count_nodes should start pointing to the list's head item and iterate as long as __next of the current item is not None -- check the links, not the data!

def count_nodes(biscuit_list):
    count=0
    current = biscuit_list.get_head()
    while current is not None:
        current = current.get_next()
        count += 1
    return count

Better yet, go ahead and implement __len__ and, for convenience, __iter__ and __next__ for syntactic sugar. Put your count_nodes code into __len__, such that you can do:

print(len(biscuit_list))

and

for node in biscuit_list:
    print(node)

There's a great source for Python's magic methods, make sure to check that, it's worth a read.

Upvotes: 1

hallie
hallie

Reputation: 89

The temp items in your biscuit list are already a Node so you can go ahead and use the Node methods directly.

def count_nodes(biscuit_list):
  count=0

  temp = biscuit_list.get_head()
  while(temp is not None):
      count += 1
      temp = temp.get_next()
  return count

Upvotes: 2

Related Questions