Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit fec696a

Browse files
committed
sum list done
1 parent 5b52d20 commit fec696a

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.ctci.linkedlists;
2+
3+
import static com.ctci.linkedlists.Node.printList;
4+
5+
/**
6+
* @author rampatra
7+
* @since 2019-01-31
8+
*/
9+
public class SumLists {
10+
11+
private static Node sumLists(Node num1, Node num2) {
12+
int carry = 0;
13+
int sum;
14+
Node sumList = null, curr = null;
15+
while (num1 != null || num2 != null) {
16+
sum = ((num1 == null) ? 0 : num1.val) + ((num2 == null) ? 0 : num2.val) + carry;
17+
carry = sum / 10;
18+
if (sumList == null) {
19+
sumList = new Node(sum % 10);
20+
curr = sumList;
21+
} else {
22+
curr.next = new Node(sum % 10);
23+
curr = curr.next;
24+
}
25+
if (num1 != null) num1 = num1.next;
26+
if (num2 != null) num2 = num2.next;
27+
}
28+
if (carry != 0) {
29+
curr.next = new Node(carry);
30+
}
31+
return sumList;
32+
}
33+
34+
public static void main(String[] args) {
35+
Node l1 = new Node(9);
36+
l1.next = new Node(9);
37+
l1.next.next = new Node(9);
38+
39+
Node l2 = new Node(9);
40+
l2.next = new Node(9);
41+
l2.next.next = new Node(9);
42+
43+
printList(l1);
44+
printList(l2);
45+
printList(sumLists(l1, l2));
46+
System.out.println("-----------");
47+
48+
l1 = new Node(9);
49+
l1.next = new Node(9);
50+
51+
l2 = new Node(9);
52+
l2.next = new Node(9);
53+
l2.next.next = new Node(9);
54+
55+
printList(l1);
56+
printList(l2);
57+
printList(sumLists(l1, l2));
58+
System.out.println("-----------");
59+
60+
l1 = null;
61+
l2 = new Node(9);
62+
l2.next = new Node(9);
63+
l2.next.next = new Node(8);
64+
65+
printList(l1);
66+
printList(l2);
67+
printList(sumLists(l1, l2));
68+
}
69+
}

0 commit comments

Comments
 (0)