I have a weird issue being able to traverse through a custom linked list. Here is the code for traversal.
from typing import Optional
class ListNode:
def __init__(self, val, next_node=None):
self.val = val
self.next_node = next_node
@property
def value(self):
return self.val
def __str__(self):
return f"Value={self.val}, Next node available={self.next_node.value if self.next_node != None else -1}"
__dict__ = ("val", "next_node",)
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[list]:
result_arr = []
l1_running = l1 != None
curr_node = l1
print("***** Start traversing L1 only ******")
while l1_running:
print(curr_node)
if curr_node.next_node:
l1_running = True
curr_node = curr_node.next_node
else:
l1_running = False
curr_node = None
print("***** End traversing L1 only ******")
print(result_arr)
return result_arr
def list_node_builder(self, l1: list[str], l2: list[int]) -> list[int]:
print("***** Start building Linked List ******")
l1_list_nodes = []
l2_list_nodes = []
for index, num in enumerate(l1):
if index == len(l1) - 1:
new_node = ListNode(num)
l1_list_nodes.append(new_node)
print(new_node)
else:
new_node = ListNode(num, ListNode(l1[index+1]))
print(str(new_node))
l1_list_nodes.append(new_node)
for index, num in enumerate(l2):
if index == len(l2) -1:
l2_list_nodes.append(ListNode(num))
else:
l2_list_nodes.append(ListNode(num, ListNode(l2[index+1])))
print("***** Done building Linked List ******")
return self.addTwoNumbers(l1_list_nodes[0], l2_list_nodes[0])
When I am trying to call this using the following code:
from addNumbers import Solution
if __name__ == "__main__":
s = Solution()
print(s.list_node_builder(l1=["a","b","c","d","e","f","g"], l2=[9,9,9,1]))
My output is like this:
/Users/shyam/codespaces/python_projects/.venv/bin/python /Users/shyam/codespaces/python_projects/index.py
***** Start building Linked List ******
Value=a, Next node available=b
Value=b, Next node available=c
Value=c, Next node available=d
Value=d, Next node available=e
Value=e, Next node available=f
Value=f, Next node available=g
Value=g, Next node available=-1
***** Done building Linked List ******
***** Start traversing L1 only ******
Value=a, Next node available=b
Value=b, Next node available=-1
***** End traversing L1 only ******
[]
[]
Process finished with exit code 0
I am not able to understand why building the linked list looks fine and the next_node
is properly set, but when I traverse the list using the head, I get stopped out on the 2nd node.
That's because you're trying to link the nodes in the linked list with the items in the static list that you're passing to list_node_builder
. You should add a node to the 1l_list_nodes, then when adding a new node, link the last node to the current node. Here's the code (this should answer your question, you still have to make changes to the rest of the code accordingly):
from typing import Optional
class ListNode:
def __init__(self, val, next_node=None):
self.val = val
self.next_node = next_node
@property
def value(self):
return self.val
def __str__(self):
return f"Value={self.val}, Next node available={self.next_node.value if self.next_node != None else -1}"
__dict__ = ("val", "next_node",)
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[list]:
result_arr = []
l1_running = l1 != None
curr_node = l1
print("***** Start traversing L1 only ******")
while l1_running:
print(curr_node)
if curr_node.next_node:
l1_running = True
curr_node = curr_node.next_node
else:
l1_running = False
curr_node = None
print("***** End traversing L1 only ******")
print(result_arr)
return result_arr
def list_node_builder(self, l1: list[str], l2: list[int]) -> list[int]:
print("***** Start building Linked List ******")
l1_list_nodes = []
l2_list_nodes = []
# Here
for index, num in enumerate(l1):
new_node = ListNode(num)
l1_list_nodes.append(new_node)
if index !=0:
l1_list_nodes[index-1].next_node = l1_list_nodes[index]
for index, num in enumerate(l2):
new_node = ListNode(num)
l2_list_nodes.append(new_node)
if index !=0:
l2_list_nodes[index-1].next_node = l2_list_nodes[index]
print("***** Done building Linked List ******")
return self.addTwoNumbers(l1_list_nodes[0], l2_list_nodes[0])
if __name__ == "__main__":
s = Solution()
print(s.list_node_builder(l1=["a","b","c","d","e","f","g"], l2=[9,9,9,1]))