Deleting a node from the position indicated by the index

Question:

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.

Asked By: Daniel

||

Answers:

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
Answered By: trincot

I m not going to give complete answer ,but point out some issues with your code.

  1. if index == 0 and your list is empty, it will throw exception when you call delete. You need to change it to if index == 0 and self.head:

  2. In the for loop, if index == 1 what do you think will happen with for i in range(0) ? It will never go into the loop.

  3. current.next = current.next is not going to have any effect. Instead I believe you should have self.head.next = current.next after checking current is not NULL.

Answered By: SomeDude