How To Generate A Linked-list From A Standard List In Python
As part of a bigger project, I'm trying to generate a linked-list from a standard list. I've already looked through some topics regarding this problem on SO (e.g. here) but most of
Solution 1:
You are in the right direction, just take care of the pointer allocation after adding new node, also keep a reference to the first node and return that:
defpopulate(self, in_list):
# creating the head node
curr = ListNode(in_list[0])
head = curr
# iterating over input listfor i in in_list[1:]:
temp = ListNode(i)
curr.next = temp
curr = temp
return head
Complete code:
classListNode(object):
def__init__(self, x):
self.val = x
self.next = NoneclassCreator:
defpopulate(self, in_list):
# creating the head node
curr = ListNode(in_list[0])
head = curr
# iterating over input listfor i in in_list[1:]:
temp = ListNode(i)
curr.next = temp
curr = temp
return head
# Below the manual approach for a list of four elements/nodes# manual_list = ListNode(1)# manual_list.next = ListNode(2)# manual_list.next.next = ListNode(3)# manual_list.next.next.next = ListNode(4)
inputs = [1,2,3,4]
result = Creator().populate(inputs)
while result:
print(result.val)
result = result.next
Post a Comment for "How To Generate A Linked-list From A Standard List In Python"