I am having a issue, where my program is not deleting a node, which is passed in.
The delete function is following:
def delete(self, index):
if index == 0:
self.head = self.head.next
else:
current = self.head
for i in range(index-1):
current = current.next
current.next = current.next
self.size -= 1
The passing of the data is made by following;
if __name__ == "__main__":
L = LinkedList()
#append
L.append(4)
L.append(1)
L.append(2)
L.print()
#delete
L.delete(1)
L.print()
Excpected output:
4 -> 1 -> 2
4 -> 2
Actual output:
4 -> 1 -> 2
4 -> 1 -> 2
I know this might be partially the same as Deleting a linked-list node at a given position but I can't really get the hang of it.
CodePudding user response:
The statement:
current.next = current.next
is not changing current.next
.
Should be:
current.next = current.next.next
You'll also want to avoid running out of your list when i
is out of range:
def delete(self, index):
if not self.head or i < 0:
return # out of range
if index == 0:
self.head = self.head.next
else:
current = self.head
for i in range(index-1):
current = current.next
if not current:
return # out of range
if not current.next:
return # out of range
current.next = current.next.next
self.size -= 1
CodePudding user response:
I m not going to give complete answer ,but point out some issues with your code.
if
index == 0
and your list is empty, it will throw exception when you call delete. You need to change it toif index == 0 and self.head:
In the for loop, if
index == 1
what do you think will happen withfor i in range(0)
? It will never go into the loop.current.next = current.next
is not going to have any effect. Instead I believe you should haveself.head.next = current.next
after checkingcurrent
is not NULL.