Skip to content

Commit 8f9d15e

Browse files
committed
Add two numbers and return the reversed linked list
1 parent b190cb7 commit 8f9d15e

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.thealgorithms.datastructures.lists;
2+
3+
// Given two numbers in the form of reversed linked list
4+
// Add two numbers and return the answer in the form of reversed linked list again.
5+
// Also known as the implementation of SumList
6+
7+
class Node {
8+
int data;
9+
Node next;
10+
11+
public Node(int data) {
12+
this.data = data;
13+
this.next = null;
14+
}
15+
}
16+
17+
public class AddTwoNumbers {
18+
public Node addTwoNumbers(Node head1, Node head2) {
19+
if (head1 == null && head2 == null) {
20+
return null;
21+
}
22+
Node temp1 = head1;
23+
Node temp2 = head2;
24+
Node dummy = new Node(-1);
25+
Node temp = dummy;
26+
int carry = 0;
27+
28+
while (temp1 != null || temp2 != null) {
29+
int sum = carry;
30+
if (temp1 != null) {
31+
sum += temp1.data;
32+
}
33+
if (temp2 != null) {
34+
sum += temp2.data;
35+
}
36+
Node newNode = new Node(sum % 10);
37+
carry = sum / 10;
38+
temp.next = newNode;
39+
temp = temp.next;
40+
41+
if (temp1 != null) {
42+
temp1 = temp1.next;
43+
}
44+
if (temp2 != null) {
45+
temp2 = temp2.next;
46+
}
47+
}
48+
if (carry != 0) {
49+
Node currNode = new Node(carry);
50+
temp.next = currNode;
51+
}
52+
return dummy.next;
53+
}
54+
}

0 commit comments

Comments
 (0)