Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMona Jalal
4,302 Pointsinsert method for linked list doesn't work properly
Please have a look at the code below and let me know why insert method is wrong?
class LinkedListNode():
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def data(self):
return self.data
def next_node(self):
return self.next_node
def set_next_node(self, next_node):
self.next_node = next_node
def search(self, data):
index = 0
while self.next_node != None and self != None:
if self.data == data:
return index
else:
self = self.next_node
index += 1
return -1
def delete(self, data):
head = self
if self.data == data:
head = self.next_node
while self.next_node != None and self != None:
if self.next_node.data == data:
if self.next_node.next_node != None:
self.next_node = self.next_node.next_node
else:
self.next_node = None
else:
self = self.next_node
return head
def insert(self, index, data):
head = self
if index == 0:
tmp_node = LinkedListNode(data)
tmp_node.next_node = self
head = tmp_node
else:
idx = 0
while self.next_node != None and self != None:
if idx == index:
middle_node = LinkedListNode(data)
if self.next_node.next_node != None:
middle_node.next_node = self.next_node.next_node
else:
middle_node.next_node = None
self.next_node = middle_node
else:
self = self.next_node
idx += 1
return head
def size(self):
items = 0
while self.next_node != None and self != None:
items += 1
self = self.next_node
if self != None:
items += 1
return items
def print(self):
while self.next_node != None:
print("%s: %s" % ("current node data is", self.data))
self = self.next_node
if self.next_node == None and self != None:
print("%s: %s" % ("current node data is", self.data))
Here's the test method I've written: from LinkedListNode import *
head = LinkedListNode(3)
node1 = LinkedListNode('cat')
node2 = LinkedListNode('dog')
node3 = LinkedListNode(4)
head.set_next_node(node1)
node1.set_next_node(node2)
node2.set_next_node(node3)
print(head.search('dog'))
head.delete(3)
head.delete(4)
head.insert(1, 'fish')
print(head.size())
head.print()
Additionally please do let me know if other things are wrong or any additional suggestion about the code.