2 Add Two Numbers

1. 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
1
Input:(2 -> 4 -> 3) + (5 -> 6 -> 4)
2
3
Output:7 -> 0 -> 8
4
5
Explanation: 342 + 465 = 807.
Copied!

2. Implementation

1
/**
2
* Definition for singly-linked list.
3
* public class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) { val = x; }
7
* }
8
*/
9
class Solution {
10
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11
ListNode p1 = l1, p2 = l2;
12
ListNode dummy = new ListNode(0);
13
ListNode curNode = dummy;
14
int sum = 0;
15
16
while (p1 != null || p2 != null) {
17
if (p1 != null) {
18
sum += p1.val;
19
p1 = p1.next;
20
}
21
22
if (p2 != null) {
23
sum += p2.val;
24
p2 = p2.next;
25
}
26
27
curNode.next = new ListNode(sum % 10);
28
curNode = curNode.next;
29
sum /= 10;
30
}
31
32
if (sum != 0) {
33
curNode.next = new ListNode(sum);
34
}
35
return dummy.next;
36
}
37
}
Copied!

3. Time & Space Complexity

时间复杂度O(m + n), m为第一个list的长度,n为第二个list的长度, 空间复杂度O(1)