关于LeetCode中链表实现两数相加问题的技术咨询
Hey there! Let's tackle this LeetCode problem together—adding two numbers represented by reversed linked lists. First, let's recap the problem clearly:
给定两个非空链表,分别表示两个非负整数。数字以逆序存储,每个节点包含一个数字。将这两个数相加并以链表形式返回。可以假设除了数字0本身外,这两个数都没有前导零。
示例输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
示例输出:(7 -> 0 -> 8) (对应整数342 + 465 = 807,逆序后即为7->0->8)
I’m guessing you might have run into common pitfalls like handling different-length linked lists, passing carry values correctly, or avoiding null pointer errors when building the result. Let’s walk through a solid solution with explanations:
核心思路
- 用**虚拟头节点(dummy head)**简化结果链表的构建,不用单独处理头节点的特殊情况
- 同步遍历两个输入链表,每次取当前节点的数值(链表遍历完就用0代替)
- 计算当前位总和:
总和 = 链表1当前值 + 链表2当前值 + 上一位进位 - 当前位的数字是
总和 % 10,新的进位是总和 // 10 - 将当前位数字作为新节点添加到结果链表
- 遍历结束后,如果还有剩余进位,要额外添加一个节点存储这个进位
代码实现(Python 版本)
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode: # 虚拟头节点,方便后续返回结果链表的头 dummy = ListNode(0) current = dummy carry = 0 # 循环条件:只要还有未遍历的节点,或者还有进位 while l1 is not None or l2 is not None or carry != 0: # 取当前节点的值,为空则用0代替 val1 = l1.val if l1 else 0 val2 = l2.val if l2 else 0 # 计算总和与新的进位 total = val1 + val2 + carry carry = total // 10 current_digit = total % 10 # 添加新节点到结果链表 current.next = ListNode(current_digit) current = current.next # 移动链表指针到下一个节点 if l1: l1 = l1.next if l2: l2 = l2.next # 虚拟头节点的下一个节点就是结果的头 return dummy.next
关键细节说明
- 虚拟头节点:
dummy节点让我们不用在开头判断“结果链表是否为空”,直接从dummy.next就能拿到最终的结果头,简化了逻辑。 - 循环条件:
l1 is not None or l2 is not None or carry != 0——这个条件覆盖了所有情况:哪怕两个链表都遍历完了,只要还有进位(比如999 + 1 = 1000),我们就要额外添加一个存1的节点。 - 长短链表处理:当其中一个链表先遍历完时,用0代替它的当前值,这样就不用写额外的分支来处理长度不同的情况。
If you have specific issues (like a test case failing, or a runtime error), feel free to share the details and we can debug it together!
内容的提问来源于stack exchange,提问作者oumoum

