497 views
For Example:-
List1:- 1 2 3 4 5 9
List2:- 9 6 3
Output:- 1 2 4 4 2 2

by (5k points)
See the following running example that adds two numbers which is represented by linked list.

3. New linked list get which is in reverse order of actual addition of both linked list

public static void main(String[] args) {
l1.insert(1);
l1.insert(2);
l1.insert(3);
l1.insert(4);
l1.insert(5);
l1.insert(9);
l2.insert(9);
l2.insert(6);
l2.insert(3);

System.out.println("List1: ");
l1.print();

System.out.println("\nList2: ");
l2.print();

}

list1 = reverseList(list1);
list2 = reverseList(list2);

System.out.println("\nAfter Reverse List1: ");
print();
System.out.println("\nAfter Reverse List2: ");
print();

print();
print();
}

if(list1 == null && list2 == null)
return null;
else if(list1 == null)
return list2;
else if(list2 == null)
return list1;

int sum = 0, carry = 0, reminder = 0;

//Both having same number of nodes
while(list1 != null && list2 != null){
sum = carry + list1.data + list2.data;
carry = sum/10;
if(carry == 0){
insert(sum);
reminder = 0;
}else{
reminder = sum%10;
insert(reminder);
}
list1 = list1.next;
list2 = list2.next;
}
//If list1 is bigger
while(list1 != null){
if(carry == 0){
insert(list1.data);
}else{
sum = carry + list1.data;
carry = sum/10;
if(carry == 0){
insert(sum);
reminder = 0;
}else{
reminder = sum%10;
insert(reminder);
}
}
list1 = list1.next;
}

//If list2 is bigger
while(list2 != null){
if(carry == 0){
insert(list2.data);
}else{
sum = carry + list2.data;
carry = sum/10;
if(carry == 0){
insert(sum);
reminder = 0;
}else{
reminder = sum%10;
insert(reminder);
}
}
list2 = list2.next;
}
if(carry > 0){
insert(carry);
}
}

private Node reverseList(Node list) {
Node prev = null;
while(list.next != null){
Node next = list.next;
list.next = prev;
prev = list;
list = next;
}

list.next = prev;

return list;
}

private class Node{
int data;
Node next;
Node(int data){
this.data = data;
}
}

public void insert(int data){
Node newNode = new Node(data);
}else{
while(curr.next != null){
curr = curr.next;
}
curr.next = newNode;
}
}

public void print(){
return;
while(curr != null){
System.out.print(curr.data + " ");
curr = curr.next;
}
}

}

Output:-
List1:
1 2 3 4 5 9
List2:
9 6 3
After Reverse List1:
9 5 4 3 2 1
After Reverse List2:
3 6 9
2 2 4 4 2 1
1 2 4 4 2 2
by (5k points)
Following Methods to add two numbers which is represented by linked list.

1. Convert linked list to number
2. Add both numbers which you have converted linked list to number
3. Now convert number to linked list and get result.

int firstNum = listToNumber(list1);
int secondNum = listToNumber(list2);
int sum = firstNum + secondNum;
}

private int listToNumber(Node list) {
if(list == null)
return 0;
int num = 0;
while(list != null){
if(num == 0){
num = list.data;
}else{
num = num * 10 + list.data;
}
list = list.next;
}
return num;
}

int num = sum;
while(num > 0){
int reminder = num%10;
num = num/10;
}
}

Node node = new Node(num);
}else{