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.
這道題其實思路就是附加了一個鏈表,兩數相加,改成了三數相加,如果l1和l2相加大於10,另外一數就是 ,則另外一個鏈表的下一個節點的值爲1,不大於10,下一個節點的值爲0。其次就是特殊情況的處理。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = ListNode(0)
cur1 = ListNode(1)
cur0 = ListNode(0)
a_list = []
while l1!= None or l2!= None:
if l1.val + l2.val +l3.val >=10:
a_list.append(l1.val +l2.val +l3.val -10)
l3 = l3.next
l3 = cur1
else:
a_list.append(l1.val+l2.val+l3.val)
l3 = l3.next
l3 = cur0
l2 = l2.next
l1 = l1.next
if l1 == None and l2 != None:
l1 = cur0
if l1 != None and l2 == None:
l2 = cur0
if l3.val == 1:
a_list.append(1)
return a_list
代碼先這樣,後期刷第二遍的時候再做優化。