Catalogue
Question
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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Analysis
这一道题在一刷的时候还没有特别的解决技巧,基本思路是分为三种情况:
- 两个链表节点都有值的时候,将两个节点的值加起来赋给新节点;
- 只有链表一的节点有值,将链表一节点的值赋给新节点
- 只有链表二的节点有值,将链表一节点的值赋给新节点
这是最先想到的解法,代码在下方Method One
中展示。
比较简化的思路是,只要链表一或者链表二存在有效值,就继续循环。如果链表一有值而链表二没有,则给链表二的节点赋值 ListNode(0)
用于计算;反之给链表一的节点赋值 ListNode(0)
。这样操作省去了分情况讨论的复杂性,这个算法的代码在 Method Optimum
中展示。另外需要注意的是,当两个值相加超过9时,仅保留个位上的数字,并进位,因此需要额外的空间保存进位信息。
Code
1 | class Solution: |