File tree 1 file changed +69
-0
lines changed
src/main/java/com/ctci/linkedlists
1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments