Problem 2 of LeetCode provides the user with two linked lists. The digits of the linked lists are in reverse order, and the user must return the sum of the two values as a linked list.
My solution may not be the most efficient, but I want to figure out how to modify it for my own understanding of linked lists and trees.
I initialized strings to hold the digits of each linked list, then calculated the total based on both strings reversed.
I would then insert the digits of the sum into a list, and start popping the last value one at a time, adding the popped value to a new linked list until the list is empty.
However when I create my linked list called 'res', the initial value is initialized as 0. Can someone suggest a revision I can make to overcome this particular issue?
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
v1 = ""
v2 = ""
temp = []
while l1 and l2:
v1 += str(l1.val)
v2 += str(l2.val)
l1 = l1.next
l2 = l2.next
v1 = v1[::-1]
v2 = v2[::-1]
total = int(v1) + int(v2)
for char in str(total)[::-1]:
temp.append(char)
res = ListNode()
curr = res
while temp:
curr.next = ListNode(temp.pop(0))
curr = curr.next
return res
Here's how you would take a list of values and turn them into a linked list
temp = [1, 2, 3, 4]
curr = None # Our lists start as empty, which is indicated by the absence of a node
for item in temp:
curr = ListNode(item, curr) # We create a new node that points to our current node, then
# redirect our local reference to point to that node
# Remember that the right hand side is calculated first
# which makes this safe
This would leave us with 4 -> 3 -> 2 -> 1