Skip to content

Commit e94073e

Browse files
committed
Merge pull request careermonk#4 from Amay22/master
Added function to add two reversed Numbers in LL
2 parents 9bfd176 + 23e7f53 commit e94073e

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

Diff for: src/chapter03linkedlists/AddNumbersFromList.java

+23-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,28 @@
1212

1313
package chapter03linkedlists;
1414
public class AddNumbersFromList {
15+
// NOTE : the input parameters and output LL is reversed.
16+
public static ListNode addTwoReversedNumbers(ListNode l1, ListNode l2) {
17+
int carry = 0;
18+
ListNode head = new ListNode(0);
19+
ListNode sum = head;
20+
while (l1 != null || l2 != null) {
21+
if (l1 != null) {
22+
carry += l1.data;
23+
l1 = l1.next;
24+
}
25+
if (l2 != null) {
26+
carry += l2.data;
27+
l2 = l2.next;
28+
}
29+
sum.next = new ListNode(carry % 10);
30+
sum = sum.next;
31+
carry /= 10;
32+
}
33+
sum.next = carry == 1 ? new ListNode(1) : null;
34+
return head.next;
35+
}
36+
1537
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
1638
if(l1 == null)
1739
return l2;
@@ -44,4 +66,4 @@ public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
4466
}
4567
return head.next;
4668
}
47-
}
69+
}

0 commit comments

Comments
 (0)