I have created a linkedlist class with deletion method. I have written the code to delete the node no matter what situation it is, like
- if deleting node is self.head
- if only one node present in linkedlist
- Any node from linked list
Code:
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def __str__(self):
temp_node = self.head
result = ''
while temp_node is not None:
result += str(temp_node.value)
if temp_node.next is not None:
result += ' -> '
temp_node = temp_node.next
return result
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
self.length += 1
def get(self, index):
temp_node = self.head
if self.length == 1 or index == 0:
return self.head
else:
for _ in range(index):
temp_node = temp_node.next
return temp_node
def remove(self,index):
if (index == 0):
popped_node = self.head
self.head = self.head.next
return popped_node
elif (self.length == 1):
popped_node = self.head
self.head = self.tail = None
return popped_node
else:
temp_head = self.head
for _ in range(index-1):
temp_head = temp_head.next
prev_node = temp_head
popped_node = prev_node.next
prev_node.next = popped_node.next
popped_node.next = None
return popped_node
but eventually it is giving below error
Error details 5 != 4 : Removing head node failed
What is the issue here?
In
remove, you're not updating thelengthattribute, and except for one case you are not updatingself.taileither (when the last node is removed).Not a problem, but you don't need to distinguish the middle case with the
elsecase.Correction: