sri2097 [EMAIL PROTECTED] writes:
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 -
Generally very nice.
# 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
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 ?
Sure:
node = None
for i in range(n):
node = linklist(i, node)
# Node now points to a linked list of n nodes, counting down as you traverse
# the list.
Any general criticisms about the code are also welcome...
Well, your __str__ on linklist makes printing node.data, node.link
equivalent to printing node.data, node.link.data, which is
confusing. Maybe you want to make the __str__ method different?
Also, the while loop in printing can be shortened a bit. The canonical
loop scanner looks like:
while node:
process(node)
node = node.link
You have a slightly different process for the last node, which
requires a conditional in the loop. By re-arranging things so the
difference happens on the first node, you process the first node
outside the loop, and drop the conditional in the loop:
def printing2(node):
print node.data, node.link,
node = node.link
while node:
print --, node.data, node.link,
node = node.link
print \nAll nodes printed
Ok, part of the difference was printing the trailing newline. I moved
that to the final print statement to make it work right.
mike
--
Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
--
http://mail.python.org/mailman/listinfo/python-list