manbearpig1 manbearpig1 - 4 months ago 11
Python Question

Adding nodes to a linked list in Python

The addToList() function takes a value as an argument. Values are passed to the addToList() function many times consecutively.

def addToList(value):
node = {}
node["data"] = value
node["next"] = None
head = node


The question is: how do I create many different nodes? Each value that comes in should be assigned to a node. Only the first node should be equal to head. As of now, I'm creating one node, giving it a value, and then when the next value comes in I overwrite the node I had made instead of creating a new one. How would each new node point to a different ["next"]? If I know my values ahead of time, I can program each node manually. I don't understand how to generate new and unique nodes when I don't know how many values I will have, and they are being fed to a function.

Answer

There are pretty much two possibilities (unless you want to go to object oriented code, then there is a third option). For simplicity I assume that we add element in front (and not at the end) of the list.

global scope

Meaning that you have just one list at the time

head = None
def addToList(value):
    global head
    head = {'value': value, 'next': head}

addToList(3)
addToList(5)
addToList(11)
print head

or using actual lists:

actual_list = []
def addToList(value):
    global actual_list
    actual_list.append(value)

addToList(3)
addToList(5)
addToList(11)
print actual_list

two arguments

def addToList(value, head):
    return {'value': value, 'next': head}

head = None
head = addToList(3, head)
head = addToList(5, head)
head = addToList(11, head)
print head

and again using actual lists

def addToList(value, actual_list):
    actual_list.append(value)

actual_list = []
addToList(3, actual_list)
addToList(5, actual_list)
addToList(11, actual_list)
print actual_list
Comments