Reputation: 287
I have defined the LinkedList
class below. I was able to implement all other methods except for the __str__
method, can someone tell me how to define this method. The Node
class has already been defined and I can use Node()
, get_data()
, set_data()
, get_next()
and set_next()
class LinkedList:
def __init__(self):
self.head = None
self.count = 0
def is_empty(self):
return self.count == 0
def size(self):
return self.count
def add(self, item):
new_node = Node(item)
new_node.set_next(self.head)
self.head = new_node
self.count += 1
def search(self, item):
current = self.head
while current != None:
if current.get_data() == item:
return True
else:
current = current.get_next()
return False
def remove(self, item):
found = False
current = self.head
previous = None
while current != None and not found:
if current.get_data() == item:
found = True
else:
previous = current
current = current.get_next()
if found:
if previous == None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
self.count -= 1
else:
raise ValueError("remove(" + str(item) + "). " + str(item) + " is not in list")
def clear(self):
while (self.head != None):
temp = self.head
self.head = self.head.next
temp = None
def __str__(self): #My doubt is here
current = self.head
return "Head --> {}".format(current)
current = current.get_next()
Test:
l_list = LinkedList()
print(l_list)
l_list.add(1)
l_list.add(2)
print(l_list)
Output expected:
Head --> None
Head --> 2 --> 1
output received:
Head --> None
Head --> <__main__.Node object at 0x7f39f7d14b80>
Test:
l_list = LinkedList()
l_list.add("hello")
l_list.add("world")
print(l_list)
l_list.clear()
print(l_list)
output expected:
Head --> world --> hello
Head --> None
output recd:
Head --> <__main__.Node object at 0x7f39f7d7cf10>
Head --> None
Upvotes: 0
Views: 348
Reputation: 1478
Here you print the object of Node, For fixing just call get_data method for each Node, and get next Node:
def __str__(self): #My doubt is here
current = self.head
s = "Head -->"
while current:
s+=" {} -->".format(current.get_data())
current = current.get_next()
s += " None"
return s
The output of:
l_list = LinkedList()
print(l_list)
l_list.add(1)
l_list.add(2)
print(l_list)
will be:
Head --> None
Head --> 2 --> 1 --> None
Upvotes: 1