1

and make a singly linked list while looping? like so:

def make_nodes(n):
    head_node = Node(0,None)
    for i in range(1,n):
        node("i") = Node(i, None)
        #somehow link them 

so that the nodes will be named: node1 node2 node3 ... node9

Many thanks in advance!

mhawke
  • 84,695
  • 9
  • 117
  • 138
AAAgradebeef
  • 55
  • 1
  • 2
  • 6

2 Answers2

1

No, but you can use a list:

def make_nodes(n):
    nodes = []
    nodes.append(Node(0,None))    # head node
    for i in range(1, n):
        nodes.append(Node(i, None))
        nodes[i-1].next = nodes[i]    #somehow link them          
    return nodes

nodes = make_nodes()
head = nodes[0]
second = nodes[1]
last = nodes[-1]

You could also use a dictionary, and use the node number as the key. But a list seems more natural in this case.

But why would you want to do this? You might as well just use a Python list of Nodes. Creating the node list can be easily done with a list comprehension. Iterating over the list could then be done with a simple for loop:

nodes = [Node(i) for i in range(n)]

for node in nodes:
    print(node.payload)
mhawke
  • 84,695
  • 9
  • 117
  • 138
0

You can use dictionaries and/or list to do what you are trying to achieve there.

But still if you are trying to test some data structure(s) for learning purpose you can create a class Node and work on it.

class Node(object):
    __data = None
    __ref_to_next = None

    def __init__(self, d):
        self.set_data(d)

    def set_data(self, d):
        self.__data = d

    def set_ref_to_next(self, r):
        self.__ref_to_next = r

    def append_a_node(self, new_node):
        cnode = self
        while cnode.__ref_to_next != None:
            cnode = cnode.__ref_to_next
        cnode.set_ref_to_next(new_node)

    def traverse(self):
        cnode = self
        while cnode.__ref_to_next != None:
            print cnode.__data
            cnode = cnode.__ref_to_next


def make_nodes(n):
    head_node = Node(0)
    for i in range(1,n):
        new_node = Node(i)
        head_node.append_a_node(new_node)

You can use the append function to populate the linked list simulation.

anand
  • 1,506
  • 14
  • 28