Description
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution
时间复杂度:O(max(m, n))
空间复杂度:O(max(m, n))
核心:
注意链表长度不一致和进位即可。
1. 由于链表长度可能不一致,因此只要任一链表有值或有carray(进位),就继续计算
2. 循环中判断,链表如果无值那么就取0,并且每个链表走向下一个节点
def addTwoNumbers(self, l1, l2):
ret = dummy = ListNode(0)
carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
v_sum = v1 + v2 + carry
if (v_sum >= 10):
carry = 1
v_sum = v_sum - 10
else:
carry = 0
dummy.next = ListNode(v_sum)
dummy = dummy.next
l1 = l1.next if l1 else 0
l2 = l2.next if l2 else 0
return ret.next
--EOF--
网友评论