LeetCode Problem: Linkded List Topics

LeetCode Problem: Linkded List Topics

1. 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. For example:

1
2
3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Suppose the input lists are:

1
2
l1: 2 -> 4 -> 3 -> 2
l2: 5 -> 6 -> 4 -> null

The initial carry is set to 0, and we can use two pointers to traverse the two lists at the same time:

1
2
3
4
5
2 -> 4 -> 3 -> 2


5 -> 6 -> 4 -> null

2 + 5 + carry = 7, and the updated carry is 0. We can add 7%10 = 7 into the result list, and keep traversing the two lists:

1
2
3
4
5
2 -> 4 -> 3 -> 2


5 -> 6 -> 4 -> null

4 + 6 + carry = 10, and the updated carry should be 1. We can add 10%10 = 0 into the result list, and keep traversing the two lists:

1
2
3
4
5
2 -> 4 -> 3 -> 2


5 -> 6 -> 4 -> null

3 + 4 + carry = 8, and the updated carry is 0. We can add 8%10 = 8 into the result list, and keep traversing the two lists:

1
2
3
4
5
2 -> 4 -> 3 -> 2


5 -> 6 -> 4 -> null

2 + 0 + carry = 2, and the updated carry is 0. We can add 2%10 = 2 into the result list, and keep traversing the two lists.

After traversing the two lists, the final carry is 0, therefore final result list is 7 -> 0 -> 8 -> 2.

Here is the code:

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
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);// the head node of the result list
ListNode current = head;

ListNode p1 = l1;// pointer1
ListNode p2 = l2;// pointer2
int carry = 0;

while (p1 != null || p2 != null) {

int sum = (p1 == null ? 0 : p1.val)
+ (p2 == null ? 0 : p2.val)
+ carry;

// update carry
if (sum >= 10) {
sum %= 10;
carry = 1;
} else {
carry = 0;
}

current.next = new ListNode(sum);
current = current.next;

// update the pointers
p1 = (p1 == null ? null : p1.next);
p2 = (p2 == null ? null : p2.next);
}

// do not forget to check the final carry
// for example, if we have:
// l1: 2 -> 4 -> 3 -> 2
// l2: 5 -> 6 -> 4 -> 9
// the final carry is 1 and we need to add 1 into the
// result list
if (carry == 1) {
current.next = new ListNode(1);
}

return head.next;
}
}

class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}