Add Two Numbers II

Problem:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in forward order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Lintcode link

Example
Given 6->1->7 + 2->9->5. That is, 617 + 295.

Return 9->1->2. That is, 912.

Solution:

Revese the given two linked list.
Then use the solution presented in the solution of “Add Two Numbers” to add then together.
Finally, reverse the result linked list back.

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*************************************************************************
> File Name: AddTwoNumbersII.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Mon 16 Nov 14:27:38 2015
************************************************************************/


public class AddTwoNumbersII{
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/

public ListNode addLists2(ListNode l1, ListNode l2) {
l1 = reverse(l1);
l2 = reverse(l2);

return reverse(addLists1(l1,l2));
}

public ListNode reverse(ListNode l){
ListNode head = null;

while (l != null){
ListNode temp = l.next;
l.next = head;
head = l;
l = temp;
}

return head;
}

public ListNode addLists1(ListNode l1, ListNode l2){
if (l1 == null && l2 == null)
return null;

ListNode head = new ListNode(0);
ListNode current = head;
int carry = 0;

while (l1 != null || l2 != null){
int sum = carry;

if (l1 != null){
sum += l1.val;
l1 = l1.next;
}

if (l2 != null){
sum += l2.val;
l2 = l2.next;
}

carry = sum / 10;
current.next = new ListNode(sum % 10);
current = current.next;
}

if (carry != 0){
current.next = new ListNode(carry);
}

return head.next;
}
}