力扣 2. 两数相加

简单遍历链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
a, b, cur_num, next_ = l1, l2, 0, 0
while a and b:
total = a.val + b.val + next_
cur_num = total % 10
next_ = total // 10

a.val = cur_num
b.val = cur_num

a = a.next
b = b.next

if a:
while a:
total = a.val + next_
cur_num = total % 10
next_ = total // 10

a.val = cur_num
a = a.next
res = l1
else:
while b:
total = b.val + next_
cur_num = total % 10
next_ = total // 10

b.val = cur_num
b = b.next
res = l2

if next_ > 0:
cur = res
while cur.next:
cur = cur.next
cur.next = ListNode(next_)

return res
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信