# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ListNode dummy1, dummy2, dummy3, res_head
dummy1 = l1
dummy2 = l2
dummy3 = res_head
carry = 0
while(dummy1 != None and dummy2 != None):
curr_val = dummy1.val + dummy2.val + carry
carry = 0 # clean carry
if curr_val >= 10:
curr_val -= 10
carry = 1
curr_node = ListNode(curr_val) # add a new node
dummy3.next = curr_node # append the node to the linkedlist
dummy3 = curr_node
dummy1 = dummy1.next
dummy2 = dummy2.next # move the dummy head one step down
if dummy1 == None: # now list one is finished
while(dummy2 != None):
curr_val = dummy2.val + carry
carry = 0
if curr_val >= 10:
curr_val -= 10
carry = 1
curr_node = ListNode(curr_val)
dummy3 = curr_node
Don't actually know how to append or insert element to a linked list.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.