top of page
Writer's pictureKarl 曹

Two Sum Problem with ListNode

Intuition

The target value for each ListNode equals sum(for i,j in enumerate(list): j*10^i). After adding two values, we can create and output a new ListNode list.

Approach

  1. iterate over listnode l1 and l2 to calculate the summed-up value

  2. make the sum value into list of digits and reverse it

  3. create a new ListNode

ListNode


ListNode could be called by ListNode.next to find the next node. Thus, when creating a new final ListNode object, ini is the first node, and we initially set hd as a copy of ini, then give hd.next new value and property of class ListNode, then loop over this to create a new ListNode object.


Code


# 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
        """
        self.l1 = l1
        self.l2 = l2
        length1 = 0
        length2 = 0
        current_node1 = self.l1
        current_node2 = self.l2
        l1value = 0
        l2value = 0
        while current_node1 is not None:
            l1value = l1value + current_node1.val*(10**length1)
            length1 += 1
            current_node1 = current_node1.next
        while current_node2 is not None:
            l2value = l2value + current_node2.val*(10**length2)            
            length2 += 1
            current_node2 = current_node2.next
        final = l1value + l2value
        fv = [int(x) for x in str(final)]
        res = list(reversed(fv))
        ini = ListNode(res[0])
        hd = ini
        for i in res[1:]:
            net = ListNode(i)
            hd.next = net
            hd = hd.next
        return ini


2 views0 comments

Recent Posts

See All

Comments


bottom of page