Cooper
Cooper

Reputation: 123

Removing a node in a Linked List using Links

I want to create a remove node function that deletes the node at the location given at a count of my LinkedList in python. I know python has a built in garbage remover, so would my code look something like this?

def removeItem(self,position):
    # ListNode is a seperate file I referenced which creates a node with data and a link.
    node = ListNode.item

    count = 0

    while count != position:
        node.link = node.link.link
        count +=1

    #Node.Link should link to the next node in the sequence.
    return node

Upvotes: 1

Views: 228

Answers (1)

benscabbia
benscabbia

Reputation: 18072

Easiest way to remove a node is to create a reference to the currentNode and previousNode like below.

def removeItem(self,position):
    currentNode = ListNode
    previousNode = None
    count = 0

    while count != position:
        #quick check to make sure next node is not empty
        if currentNode.link == None:
            print("Position Invalid")
            return None

        previousNode = currentNode
        currentNode = currentNode.link      
        count +=1

    #Node.Link should link to the next node in the sequence.
    previousNode.link = currentNode.link 
    return currentNode

Basically the previousNode.link = currentNode.link is using the previousNode's next link to reference the currentNode's next link, thus the currentNode (node you wish to remove [the node in the middle]) will lose reference and eventually be picked up by the garbage collector.

Upvotes: 1

Related Questions