题目描述
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
- 注意审题,要注意题目中已经给好了链表的数据结构,我一开始当成两个list去写的,结果全不对
- 用一个临时变量保存进位的结果,且要在计算出当前位的结果之后再计算,不然会出现直接将下一位进位用的carry,参与到本位的计算中
- dummy结点是为了记住结果链表的头节点的位置,返回时直接用dummy的next节点即可
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbersfail(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
maxlen =len(l1) if len(l1) > len(l2) else len(l2)
sup_l1,sup_l2 = supplylenth(l1,l2,maxlen)
carry = [0 for i in range(maxlen + 1)]
res = [0 for i in range(maxlen + 1)]
for i in range(maxlen):
carry[i + 1] += (sup_l1[i] + sup_l2[i] + carry[i])/10
res[i] = (sup_l1[i] + sup_l2[i] + carry[i]) % 10
return res
def supplylenth(l1,l2,maxlen):
res_l1 ,resl2 = [0 for i in range(maxlen)],[0 for i in range(maxlen)]
for i in range(l1):
res_l1[i] = l1[i]
for i in range(l2):
res_l2[i] = l2[i]
return res_l1,res_l2
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
p = l1
q = l2
cur = dummy
carry = 0
while p is not None or q is not None:
x = p.val if p is not None else 0
y = q.val if q is not None else 0
cur.next = ListNode((x + y + carry) % 10)
carry = (x + y + carry) / 10
cur = cur.next
p = p.next if p is not None else None
q = q.next if q is not None else None
if carry is 1:
cur.next = ListNode(1)
return dummy.next