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.
============
Analysis:
1. Transform the first linked list to int number 1.
2. Transform the second linked list to int number 2.
3. Compute the sum of this two number.
4. Transform the result to linked list.
public class Answer {
public static LinkedListNode solution(LinkedListNode header1, LinkedListNode header2){
if(header1 == null && header2 == null) return null;
if(header1 == null) return header2;
if(header2 == null) return header1;
int number1 = 0;
int number2 = 0;
while(header1!=null){
number1 = number1*10+header1.data;
header1 = header1.next;
}
while(header2!=null){
number2 = number2*10+header2.data;
header2 = header2.next;
}
int sum = number1+number2;
LinkedListNode next = null;
if(sum==0){
next.data = 0;
next.next = null;
return next;
}
while(sum>0){
LinkedListNode node = new LinkedListNode(0, null, null);
node.data = sum%10;
node.next = next;
sum = sum/10;
next = node;
}
return next;
}
public static void main(String[] args) {
LinkedListNode list1 = AssortedMethods.randomLinkedList(5, 0, 9);
LinkedListNode list2 = AssortedMethods.randomLinkedList(4, 0, 9);
LinkedListNode list3 = solution(list1, list2);
System.out.println(" " + list1.printForward());
System.out.println("+ " + list2.printForward());
System.out.println("= " + list3.printForward());
}
}
Standard answer of the book:
1. result data = (node1 + node2 + any earlier carry) % 10
2. if node1 + node2 > 10, then carry a 1 to the next addition
3. add the tails of the two nodes, passing along the carry