2. Add Two Numbers

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.

解法

非递归

两个数字相加的可视化:342 + 465 = 807(每个节点包含一个数字,数字以相反的顺序存储。)

思路就是遍历两个链表,同时记录进位carry

一个更清晰和简洁的python解法,这里稍微改写了一些:

复杂度分析:

  • 时间复杂度:O(max(m,n))O(max(m, n)),因为最多迭代max(m,n)max(m, n)次。

  • 空间复杂度:O(max(m,n))O(max(m, n)),因为链表最长max(m,n)+1max(m, n) + 1

递归

递归的写法比较难理解,仅做为参考学习。

拓展

Follow up:

What if the the digits in the linked list are stored in non-reversed order? For example:

(342)+(465)=807(3 \to 4 \to 2) + (4 \to 6 \to 5) = 8 \to 0 \to 7

如果链表顺序反过来怎么办?

划归:先反转链表再相加

迭代反转链表:

递归反转链表:

此时问题就转化回了原始的问题,但是引进了额外的时间和空间消耗。

直接递归

???

两数相加再转成链表

把两个链表转为自然数,相加得到结果后,构造新链表。

Last updated

Was this helpful?