Reputation: 375
I am trying to convert a string of numbers into a linked list of integers. For some reason when I go to print the value of each value in the linked list, it only prints the first value. For example: a string "523" would be turned into a linked list: 5->2->3, but it's only printing the first node value 5. Can someone please help me see what I am missing? Thanks for any help!
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
total = "523"
root = None
curr_node = None
for digit in total:
if root is None:
root = ListNode(int(digit), curr_node)
else:
curr_node = ListNode(int(digit))
curr_node = curr_node.next
while root:
print(root.val)
root = root.next
Upvotes: 0
Views: 49
Reputation: 82949
The problem with your code is that assigning a new value to curr_node
does not change the None
value currently assigned to root.next
or curr_node.next
. Instead, you should keep a reference to the current/last node itself:
root = last = None
for digit in total:
if root is None:
root = last = ListNode(int(digit))
else:
last.next = last = ListNode(int(digit))
Alternatively: Creating a recursive data structure like a linked list is often easier and more "natural" using a recursive function instead of a loop:
def to_list(s):
if s:
return ListNode(int(s[0]), to_list(s[1:]))
else:
return None
root = to_list(total)
Upvotes: 1