Published
- 1 min read
Add two numbers problem linked list
Add two numbers in a given linked lists
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.

private Node addTwoNumbers(Node n, Node m, int carry) {
//we have to start from reverse linked list then move to front so its recursion
if(n == null && m == null && carry == 0) {
return null;
}
int val1 = (n !=null) ? n.val : 0;
int val2 = (m !=null) ? m.val : 0;
int cal = val1 + val2 + carry;
Node nNode = new Node(cal%10, null);
nNode.next = addTwoNumbers(n.next, m.next, cal/10);
//Last node is the node with
return nNode;
}
private class Node {
Node next ;
int val ;
Node(int v, Node n){
this.next = n;
this.val = v;
}
}