If they differ, equalise their lengths by prepending nodes with value 0 to the shorter list.
Initialize a new list with newHead = null.
Utilize recursion to traverse both lists to the end, sum corresponding nodes, handle carry-over, and append nodes to the new list until the recursion completes.
publicclassAddLinkedListForwardOrder {
publicint carry=0;
public Node newHead =null;
public Node add(Node h1, Node h2){
//first we will make sure that both the Linked list has same no of nodes// to ensure that we will append 0 in front of shorter listint h1Len = getLength(h1);
int h2Len = getLength(h2);
if(h1Len>h2Len){
int diff = h1Len-h2Len;
while(diff>0){
Node n =new Node(0);
n.next= h2;
h2=n;
diff--;
}
}
if(h1Len<h2Len){
int diff = h2Len-h1Len;
while(diff>0){
Node n =new Node(0);
n.next= h1;
h1=n;
diff--;
}
}
Node newHead = addBackRecursion(h1, h2);
//check for the carry forward, if not 0 then we need to create another node for the end//example adding 1->1 and 9->9 then recursive function will return 0->0 and carry =1if(carry!=0){
Node n =new Node(carry);
n.next= newHead;
newHead = n;
}
return newHead;
}
public Node addBackRecursion(Node h1, Node h2){
if(h1==null&& h2==null){
returnnull;
}
addBackRecursion(h1.next, h2.next);
int a = h1.data+ h2.data+ carry;
carry=0;
//System.out.println(a);if(a>=10){
carry =1;
a = a%10;
}
Node n =new Node(a);
if(newHead==null){
newHead =n;
}else{
n.next= newHead;
newHead = n;
}
//carry=0;return newHead;
}
publicintgetLength(Node head){
int len=0;
while(head!=null){
len++;
head = head.next;
}
return len;
}
}
Input lists might have different sizes, so it’s necessary to determine their lengths. Although one could normalise the lists by adding leading zeros to the shorter one, this would consume additional memory, so this step will be skipped.
Iterate over the lists, calculate the sum of nodes, and place the result in a new list. The resulting list will be built in reverse order without tracking the carry value. See step 1 below in the diagram.
Normalize the resulting list by traversing from the head (lowest order node), adjusting node values (val % 10), storing the carry value, and reversing the list again. See step 2 in above diagram.
If the carry value is greater than zero after normalisation, create a new node and set it as the new head of the result list.