Deleting a node from the position indicated by the index

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.

>Solution :

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

Leave a Reply