演算法 2025-08-19

LeetCode -- 2. Add Two Numbers

兩個逆序儲存的鏈結串列相加。用 dummy head 搭配 carry 變數逐位相加,是練習 linked list 指標操作的經典題。

#LeetCode#Linked List#Python

Description

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Solution

# 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]:
        dummyhead = ListNode(0)
        current = dummyhead
        carry = 0

        while l1 or l2 or carry:
            l1val = l1.val if l1 else 0
            l2val = l2.val if l2 else 0
            sum = l1val + l2val + carry
            carry = sum // 10
            newNode = ListNode(sum%10)
            current.next = newNode
            current = newNode
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummyhead.next

如果對 linked list 的概念還不熟悉,可以參考 Link list in python 這篇教學。