---
# System prepended metadata

title: Leetcode 2. Add Two Numbers
tags: [Linked List, Leetcode]

---

## 題解

```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]:
        output = ListNode()
        cur = output
        pre = 0
        while l1 or l2 or pre: # 如果 l1 or l2 都跑完 要檢查是否需要進位
            sum = 0 + pre
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            cv = sum % 10
            pre = sum // 10
            cur.next = ListNode(cv)
            cur = cur.next
        
        return output.next
```