445.两数相加Ⅱ
给你两个 非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例1:
输入:l1 = [7,2,4,3], l2 = [5,6,4]
输出:[7,8,0,7]
示例2:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[8,0,7]
示例3:
输入:l1 = [0], l2 = [0]
输出:[0]
提示:
- 链表的长度范围为
[1, 100]
0 <= node.val <= 9
- 输入数据保证链表代表的数字无前导 0
**进阶:**如果输入链表不能翻转该如何解决?
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
p, q = l1, l2
n1, n2 = 0, 0
while p:
p = p.next
n1 += 1
while q:
q = q.next
n2 += 1
l3 = ListNode()
p, q, j = l1, l2, l3
while p and q:
if n1 > n2:
x = p.val
y = 0
n1 -= 1
p = p.next
elif n2 > n1:
x = 0
y = q.val
n2 -= 1
q = q.next
else:
x = p.val
y = q.val
n1 -= 1
n2 -= 1
p = p.next
q = q.next
if x + y >= 10:
node = ListNode(x+y-10)
j.val += 1
else:
node = ListNode(x+y)
j.next = node
j = j.next
pre = None
cur = l3
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
#return pre
kk = pre
while kk:
if kk.val >= 10:
kk.val -= 10
if kk.next:
kk.next.val += 1
else:
node = ListNode(1)
kk.next = node
kk = kk.next
pre1 = None
cur1 = pre
while cur1:
nxt1 = cur1.next
cur1.next = pre1
pre1 = cur1
cur1 = nxt1
if pre1.val == 0:
return pre1.next
else:
return pre1
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
pre1 = None
cur = l1
while cur:
nxt = cur.next
cur.next = pre1
pre1 = cur
cur = nxt
#return pre1
pre2 = None
cur = l2
while cur:
nxt = cur.next
cur.next = pre2
pre2 = cur
cur = nxt
#return pre2
cur = l3 = ListNode()
carry = 0
while pre1 or pre2 or carry:
s = carry + (pre1.val if pre1 else 0) + (pre2.val if pre2 else 0)
cur.next = ListNode(s % 10)
carry = s // 10
cur = cur.next
if pre1:
pre1 = pre1.next
if pre2:
pre2 = pre2.next
#return l3.next
pre3 = None
cur = l3.next
while cur:
nxt = cur.next
cur.next = pre3
pre3 = cur
cur = nxt
return pre3
不翻转链表:把单链表先依次储存到栈里,再依次出栈。