原始题目:
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.
题目翻译:
用两个非空的链表表示两个非负的整数,这两个数是被逆序存储的,并且每一个结点包含一个单独的数字。计算这两个数的和,并以链表的形式返回结果。
算法分析:
此题有很多种解法,一、直接遍历两个单链表计算,注意超过10要进位;二、递归方式;三、分情况讨论计算,两个单链表一样长直接计算,不一样长又要分情况讨论,l1还是l2长等等。
下面是Java的算法代码,直接遍历两个单链表计算
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode temp = new ListNode(0);
ListNode result = temp;
int value1 = 0;
int value2 = 0;
while (l1 != null && l2 != null) {
value2 = (l1.val + l2.val + value1) % 10;
value1 = (l1.val + l2.val + value1) / 10;
temp.next = new ListNode(value2);
l1 = l1.next;
l2 = l2.next;
temp = temp.next;
if (l1 == null && l2 == null) {
break;
}
if (l1 == null) {
l1 = new ListNode(0);
}
if (l2 == null) {
l2 = new ListNode(0);
}
}
if (value1 != 0) {
temp.next = new ListNode(value1);
}
return result.next;
}
}
复杂度分析:
时间复杂度:O(max(m+n)),假设m,n分别代表两个单链表的长度。
空间复杂度:O(max(m+n)),新的单链表最大长度为max(m+n)+1。