Some codes in Python.


  • 0
    Z

    Some codes in Python. Comments are very welcome! I also used stack, which is kind of cheating because stack is another kind of reversion.

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            
            head = None
            carry = 0
            ptr1, ptr2 = [], []
            
            while l1 != None:
                ptr1.append(l1.val)
                l1 = l1.next
            while l2 != None:
                ptr2.append(l2.val)
                l2 = l2.next
            
            while True:
                if ptr1 == [] and ptr2 == [] and carry == 0:
                    break
                else:
                    tempNode = ListNode(0)
                    tempNode.next = head
                    head = tempNode
                    
                carry += 0 if ptr1 == [] else ptr1.pop()
                carry += 0 if ptr2 == [] else ptr2.pop()
                head.val = carry % 10
                carry = carry / 10
                
            return head
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.