leetcode解题: Add Two Numbers (2)

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解法1:O(N + M) Time + O(1) Space

这题的坑是leetocde的OJ可能会TLE,要用tail.next = new ListNode(temp)就可以过了。
Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
int carry = 0;
while (l1 != null && l2 != null) {
int val = l1.val + l2.val + carry;
int digit = val % 10;
carry = val / 10;
ListNode temp = new ListNode(digit);
tail.next = temp;
tail = tail.next;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
int val = l1.val + carry;
int digit = val % 10;
carry = val / 10;
tail.next = new ListNode(digit);
tail = tail.next;
l1 = l1.next;
}
while (l2 != null) {
int val = l2.val + carry;
int digit = val % 10;
carry = val / 10;
tail.next = new ListNode(digit);
tail = tail.next;
l2 = l2.next;
}
if (carry != 0) {
tail.next = new ListNode(carry);
}
return dummy.next;
}
}