Skip to content

Instantly share code, notes, and snippets.

@cashlo
Created July 19, 2018 20:49
Show Gist options
  • Save cashlo/c45ab6fc81ab9b279c121b4d76fd607d to your computer and use it in GitHub Desktop.
Save cashlo/c45ab6fc81ab9b279c121b4d76fd607d to your computer and use it in GitHub Desktop.
# 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
"""
carry = 0
c1 = l1
c2 = l2
head = ListNode(None)
last = None
current = head
while c1 is not None or c2 is not None or carry:
current_sum = carry
if c1 is not None:
current_sum += c1.val
c1 = c1.next
if c2 is not None:
current_sum += c2.val
c2 = c2.next
carry = 0
if current_sum >= 10: carry = 1
current_sum %= 10
current.val = current_sum
current.next = ListNode(None)
last = current
current = current.next
last.next = None
return head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment