Linked List Implementation using python

We can implement linked list using python using the class concept.

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

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

ll.list_print()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s