Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my linked list size function not working as intended?

I used the following code to define my linked list, nodes and a few functions.

class node:
      def __init__(self,node_data):
        self.__data=node_data
        self.__next=None
  
  def get_data(self):
    return self.__data
  
  def set_data(self,node_data):
    self.__data=node_data
  
  data=property(get_data,set_data)

  def get_next(self):
    return self.__next
  
  def set_next(self,node_next):
    self.__next=node_next

  next=property(get_next,set_next)

  def __str__(self):
    return str(self.__data)

class unordered_list:
  def __init__(self):
    self.head=None
  
  def is_empty(self):
    return self.head==None

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

  def size(self):
    current=self.head
    count=0
    while current is not None:
      count=count+1
      current=current.next
    
    return count

  def search(self,item):
    
    current=self.head
    while current is not None:
      if current.data==item:
        return True
      current=current.next
    
    return False

I use the following code to set up a test list:

my_list=unordered_list()
my_list.add(31)
my_list.add(77)
my_list.add(17)
my_list.add(93)
my_list.add(26)
my_list.add(54)

However when I run the following command I do not get the right output:-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my_list.size()

Output:

1

Expected Output:-

6

Can someone please tell me where my error might be?

>Solution :

You need to call set_next, not assign something to that. So try replacing

temp.set_next=self.head

with

temp.set_next(self.head)

in your definition of add.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading