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不一样长的情况。
 class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = cur = ListNode(0)
carry = 0 while l1 or l2:
a = l1.val if l1 else 0
b = l2.val if l2 else 0 sum = a+b+carry
cur.next = ListNode(sum%10)
carry = sum/10
cur = cur.next if l1:
l1 = l1.next
if l2:
l2 = l2.next if carry > 0:
cur.next = ListNode(1) return dummy.next
 
上一篇:【百度地图API】——国内首款团购网站的地图插件


下一篇:Maplace.js – 小巧实用的 jQuery 谷歌地图插件