标签:log tor pre tco while res node mon leetcode
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 and l2, if l1, if l2 来处理两个list不一样长的情况。
1 def addTwoNumbers(l1, l2): 2 3 dummy = cur = NodeList(0) 4 carry = 0 5 while l1 and l2: 6 a = l1.val if l1 else 0 7 b = l2.val if l2 else 0 8 sum = a + b + carry 9 cur.next = ListNode(sum%10) 10 carry = sum/10 11 12 if l1: 13 cur.next = l1 14 if l2: 15 cur.next = l2 16 17 if carry > 0: 18 cur.next = ListNode(1) 19 20 return dummy.next
标签:log tor pre tco while res node mon leetcode
原文地址:http://www.cnblogs.com/lettuan/p/6168434.html