Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading