Leetcode #2 Add two number

Q: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

 
keys: 1. 使用dummy node记录head. 
2. 对于两个list的操作,一般使用 while l1 or l2, if l1, if l2 来处理两个list不一样长的情况。

 1 class Solution(object):
 2     def addTwoNumbers(self, l1, l2):
 3         """
 4         :type l1: ListNode
 5         :type l2: ListNode
 6         :rtype: ListNode
 7         """
 8         dummy = cur = ListNode(0)
 9         carry = 0
10         
11         while l1 or l2:
12             a = l1.val if l1 else 0
13             b = l2.val if l2 else 0
14             
15             sum = a+b+carry
16             cur.next = ListNode(sum%10)
17             carry = sum/10
18             cur = cur.next
19             
20             if l1:
21                 l1 = l1.next
22             if l2:
23                 l2 = l2.next
24         
25         if carry > 0:
26             cur.next = ListNode(1)
27             
28         return dummy.next

 

 

 
posted @ 2016-12-13 03:35  lettuan  阅读(188)  评论(0编辑  收藏  举报