Link List in Python

sri2097 srikar2097 at gmail.com
Thu Jan 12 11:45:36 EST 2006


Hi all, I have written a Link list implementation in Python (Although
it's not needed with Lists and Dictionaries present. I tried it just
for the kicks !). Anyway here is the code -

# Creating a class comprising of node in Link List.
class linklist:
    def __init__(self, data=None,link=None):
        self.data = data
        self.link = link

    def __str__(self):
        return str(self.data)

def printing(node):
    print "-"*80
    print ("[data][link] ---> [data][link] and so on till the end")
    print "-"*80
    while 1:
        if node.link:
            print node.data, node.link,"--->",
            node = node.link
        else:
            # Printing the last node and exiting.
            print node.data, node.link
            print ("All nodes printed")
            break

def assigning():
    global node1, node2, node3, node4
    node1 = linklist([raw_input("Enter name: "), raw_input("Enter
address: ")])
    node2 = linklist([raw_input("Enter name: "), raw_input("Enter
address: ")])
    node3 = linklist([raw_input("Enter name: "), raw_input("Enter
address: ")])
    node4 = linklist([raw_input("Enter name: "), raw_input("Enter
address: ")])
    # Checking to see if all the node.data are getting populated.
    print node1
    print node2
    print node3
    print node4
    print
    linking()

def linking():
    node1.link = node2
    node2.link = node3
    node3.link = node4
    # Passing the node1 to the print function so that it prints the
rest of the nodes using the links.
    printing(node1)

if __name__ == "__main__":
    assigning()


Doubt -
Now, Here I needed only 4 nodes. But what if I need more nodes. Is
there any way to create the number of nodes at runtime. Since I plan to
'import' this module later. I wouldn't know how many nodes I need even
before executing it. So, my doubt is - Is there any way to create 'n'
number of object (here nodes) at runtime ?

Any general criticisms about the code are also welcome...




More information about the Python-list mailing list