描述:
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
面对的问题:
Python 链表的构建和基本方法,结果Node练成链表
两个输入链表不等长的情况
注意进位
1. 纯属暴力也并不全对的辣鸡解法,只能通过一部分测试用例,像[2] [8,9,9,9,9]这种一直进位的情况没有解决,待晚些时候贴完全通过的代码。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
lr = head
if l1 != None and l2 != None:
jw = 0
while l2!=None and l1 !=None:
cur = l1.val + l2.val +jw
jw = 0
if cur <10:
data = cur
else:
data = cur % 10
jw = 1
tmp = ListNode(data)
head.next = tmp
head = tmp
l1 = l1.next
l2 = l2.next
if l2 == None and l1 !=None:
cur = l1.val + jw
jw = 0
if cur <10:
data = cur
else:
data = cur % 10
jwn = 1
tmp = ListNode(data)
head.next = tmp
head = tmp
if jw==1:
jwn = ListNode(1)
head.next = jwn
head = jwn
jwn = 0
head.next = l1.next
jw = 0
if l2 != None and l1 ==None:
cur = l2.val + jw
jw = 0
if cur <10:
data = cur
else:
data = cur % 10
jw = 1
tmp = ListNode(data)
head.next = tmp
head = tmp
if jw==1:
jwn = ListNode(1)
head.next = jwn
head = jwn
head.next = l2.next
jw = 0
if l2 == None and l1 ==None and jw==1:
end = ListNode(1)
head.next = end
return lr.next