-
Notifications
You must be signed in to change notification settings - Fork 199
/
Copy pathProgram.java
44 lines (34 loc) · 1.03 KB
/
Program.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
package AlgoExSolutions.Medium.SumofLinkedLists;
// import java.util.*;
/**
* * Sum Of Linked Lists
*/
class Program {
// This is an input class. Do not edit.
public static class LinkedList {
public int value;
public LinkedList next;
public LinkedList(int value) {
this.value = value;
this.next = null;
}
}
public LinkedList sumOfLinkedLists(LinkedList linkedListOne, LinkedList linkedListTwo) {
// Write your code here.
LinkedList res = new LinkedList(-1), currNode = res;
LinkedList l1 = linkedListOne, l2 = linkedListTwo;
int sum = 0, carry = 0;
while (l1 != null || l2 != null) {
int value1 = l1 != null ? l1.value : 0;
int value2 = l2 != null ? l2.value : 0;
sum = carry + value1 + value2;
currNode.next = new LinkedList(sum % 10);
carry = sum / 10;
l1 = l1 != null ? l1.next : null;
l2 = l2 != null ? l2.next : null;
currNode = currNode.next;
}
if (carry != 0) currNode.next = new LinkedList(carry);
return res.next;
}
}