Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit edef607

Browse files
Sum of linked lists
1 parent 9de1d7d commit edef607

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package crackingTheCodingInterview.chap2;
2+
3+
import me.premaseem.myLib.MySLLNode;
4+
import org.junit.Test;
5+
6+
/**
7+
* ### Sum Lists:
8+
* You have two numbers represented by a linked list, where each node contains a single digit.The digits are stored in reverse 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.
9+
* EXAMPLE
10+
* Input:(7-> 1 -> 6) + (5 -> 9 -> 2).Thatis,617 + 295. Output:2 -> 1 -> 9.Thatis,912.
11+
* <p>
12+
* FOLLOW UP
13+
* Suppose the digits are stored in forward order. Repeat the above problem. EXAMPLE
14+
* lnput:(6 -> 1 -> 7) + (2 -> 9 -> 5).That is,617 + 295. Output:9 -> 1 -> 2.Thatis,912.
15+
*/
16+
public class SumLists {
17+
// Test Driven Development by Aseem Jain
18+
@Test
19+
public void test() {
20+
21+
int[] n1 = new int[]{7, 1, 3};
22+
int[] n2 = new int[]{6, 3, 4, 8, 2};
23+
24+
MySLLNode head1 = new MySLLNode(n1);
25+
MySLLNode head2 = new MySLLNode(n2);
26+
27+
MySLLNode head3 = solution1(head1, head2);
28+
assert head3.toInt() == 64195;
29+
30+
31+
}
32+
33+
// Basic solution
34+
private MySLLNode solution1(MySLLNode h1, MySLLNode h2) {
35+
// take pointer back if DLL else reverse it
36+
// start adding last digits and savce in new ll node;
37+
// take care of carry overs
38+
39+
MySLLNode ans = null;
40+
MySLLNode newHead = null;
41+
42+
h1 = h1.reverse();
43+
h2 = h2.reverse();
44+
45+
46+
int carry = 0;
47+
48+
while (h1 != null || h2 != null || carry != 0) {
49+
int d = 0;
50+
51+
if (h1 != null) {
52+
d += h1.data;
53+
h1 = h1.next;
54+
}
55+
56+
if (h2 != null) {
57+
d += h2.data;
58+
h2 = h2.next;
59+
}
60+
61+
if (carry != 0) {
62+
d += carry;
63+
}
64+
65+
carry = d / 10;
66+
d = d % 10;
67+
MySLLNode nn = new MySLLNode(d);
68+
System.out.println(nn.data);
69+
nn.next = ans;
70+
ans = nn;
71+
newHead = nn;
72+
}
73+
74+
return newHead;
75+
}
76+
77+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /