Reputation:
I understand how to create a linked list without a loop, but I'm struggling to turn a regular list into a linked list.
def addtoHead(theList, value):
#create a new node
node={}
node['data'] = value
node['next'] = theList #connect the new node to the current head
return node #returning the new node as the head of the list
myList=None
myList=addtoHead(myList,7)
myList=addtoHead(myList,9)
myList=addtoHead(myList,10)
def printList(theList):
ptr=theList
while ptr!=None:
print(ptr['data'])
ptr=ptr['next']
Now, I want to do the same thing, except in a loop, but I'm struggling to get the logic.
def createList(pythonList):
node={}
head=None
for i in range(len(pythonList)):
node['data'] = pythonList[i]
node['next'] = head
head=pythonList[i]
printList(node)
pythonList=[7,12,14]
createList(pythonList)
My logic is that I set the data to be an element of the list, and then I connect that data type to the head. I then reset the head to be the data, and then continue. Unfortunately, this prints 14, and then I get the error:
TypeError: 'int' object is not subscriptable
This error is for print(ptr['data']). Where have I gone wrong?
Upvotes: 0
Views: 89
Reputation: 1385
So you have 2 corrections to be made in your code.
1. You need to make new node for each loop
2. head should be new node you make.
def printList(theList):
ptr=theList
while ptr!=None:
print(ptr['data'])
ptr=ptr['next']
def createList(pythonList):
head=None
for i in range(len(pythonList)):
node={}
node['data'] = pythonList[i]
node['next'] = head
head = node
printList(node)
pythonList=[7,12,14]
createList(pythonList)
Result will be
14
12
7
Upvotes: 0
Reputation: 403130
A minor change is needed. You'll need to declare a new node inside your loop.
def createList(pythonList):
head = None
for i in pythonList:
new_node = {}
new_node['data'] = i
new_node['next'] = head
head = new_node
At the end of the loop, you assign head to the new node created. In the next iteration, the next new node will reference head.
Currently, what you're doing is not changing the reference that head points to correctly (you point it to an integer after the first iteration), generating that error.
Outside the loop, run:
printList(head)
print(head)
It'll look something like this:
14
12
7
{'data': 14, 'next': {'data': 12, 'next': {'data': 7, 'next': None}}}
Which is exactly what your sans loop code does.
Upvotes: 1