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

Time:05-15

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:-

my_list.size()

Output:

1

Expected Output:-

6

Can someone please tell me where my error might be?

CodePudding user response:

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.

  • Related