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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if l1 is None: return l1 elif l2 is None: return l1 start = ListNode(0) temp = start carry = 0 while l1 or l2: sum = 0 if l1: sum += l1.val l1 = l1.next if l2: sum += l2.val l2 = l2.next sum += carry carry = 1 if sum>9 else 0 temp.next = ListNode(sum % 10) temp = temp.next if carry: temp.next = ListNode(1) temp = start.next del start return temp
链表题目,发现已经忘记怎么用链表了。。这道题用头结点会简单很多
ps.说来惭愧,很久没有刷过题了,再忙也不应该成为不刷题的借口,于是从今日立下flag,每天刷五道题。