---
title: leetcode-add-two-numbers-ii
date: 2020-04-14 23:22:39
tags:
categories: leetcode
---

### 445. 两数相加 II

[题目](https://leetcode-cn.com/problems/add-two-numbers-ii/)



<!--more-->



看到顺序的链表就想到用倒序链表的方法做，折腾了半天



```python
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
  def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
    def _reverse(l):
      if l.next:
        last = _reverse(l.next)
        l.next.next = l
        l.next = None
        return last
      return l

    l1e = _reverse(l1)
    l2e = _reverse(l2)
    new_l = ListNode(0)
    head = new_l
    c = 0
    import ipdb; ipdb.set_trace()
    while l1e and l2e:
      new_val = l1e.val + l2e.val
      if c==1:
        new_val += 1
      c = 0
      if new_val >= 10:
        new_val -= 10
        c = 1

      new_l.val = new_val
      next_n = None
      if l1e.next and l2e.next or c:
        next_n = ListNode(c)
        new_l.next = next_n
        new_l = next_n
      l1e = l1e.next
      l2e = l2e.next
    if l2e:
      l1e = l2e
    if not l1e and c:
      l1e = ListNode(0)
    while l1e:
      new_l.val = l1e.val
      new_l.val += c
      c = 0
      if new_l.val >= 10:
        c = 1
        new_l.val -= 10
      l1e = l1e.next
      if l1e:
        new_l.next = ListNode(0)
        new_l = new_l.next
      else:
        new_l.next = ListNode(1)

    return _reverse(head)

 # 84 ms	13.9 MB
```

最后面各种进位的处理应该还可以更清晰优雅一些，但是懒得搞了，感觉很蠢。翻了答案看到了小 tips，需要倒序处理的情况可以用栈。

```python
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        s1, s2 = [], []
        while l1:
            s1.append(l1.val)
            l1 = l1.next
        while l2:
            s2.append(l2.val)
            l2 = l2.next
        ans = None
        carry = 0
        while s1 or s2 or carry != 0:
            a = 0 if not s1 else s1.pop()
            b = 0 if not s2 else s2.pop()
            cur = a + b + carry
            carry = cur // 10
            cur %= 10
            curnode = ListNode(cur)
            curnode.next = ans
            ans = curnode
        return ans

作者：LeetCode-Solution
链接：https://leetcode-cn.com/problems/add-two-numbers-ii/solution/liang-shu-xiang-jia-ii-by-leetcode-solution/
来源：力扣（LeetCode）
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
```

不过就执行效率来看差不多。
