Removing a node from a linked list

Posted by lost_with_coding on Stack Overflow See other posts from Stack Overflow or by lost_with_coding
Published on 2011-01-11T06:51:34Z Indexed on 2011/01/11 7:53 UTC
Read the original article Hit count: 256

Filed under:
|
|
|

I would like to create a delete_node function that deletes the node at the location in the list as a count from the first node. So far this is the code I have:

class node:
    def __init__(self):
        self.data = None # contains the data
        self.next = None # contains the reference to the next node

class linked_list:
    def __init__(self):
        self.cur_node = None

    def add_node(self, data):
        new_node = node() # create a new node
        new_node.data = data
        new_node.next = self.cur_node # link the new node to the 'previous' node.
        self.cur_node = new_node #  set the current node to the new one.

    def list_print(self):
        node = ll.cur_node
        while node:
            print node.data
            node = node.next
    def delete_node(self,location):
        node = ll.cur_node
        count = 0
        while count != location:
            node = node.next
            count+=1
        delete node


ll = linked_list()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)

ll.list_print()

© Stack Overflow or respective owner

Related posts about python

Related posts about remove