Given two linked lists, each element of the lists is a integer. Write a function to return a new list, which is the “sum” of the given two lists.

• Part a. Given input (7->1->6) + (5->9->2), output 2->1->9.
• Part b. Given input (6->1->7) + (2->9->5), output 9->1->2.

## Code

For part a

``````Node addList(Node head1, Node head2){
int num1 = 0, count1 = 0;
int num2 = 0, count2 = 0;
int result = 0;

count1++;
}

count2++;
}
result = num1 + num2;

while(result > 0){
cur.next = new Node(result % 10);
cur = cur.next;
result /= 10;
}

}
``````

For part b

``````Node addList(Node head1, Node head2){
int num1 = 0, count1 = 0;
int num2 = 0, count2 = 0;
int result = 0;

num1 = num1 * 10 + head1.data;
count1++;
}

num2 = num2 * 10 + head2.data;
count2++;
}
result = num1 + num2;

while(result > 0){
Node temp = new Node(result % 10);
temp.next = cur.next;
cur.next = temp;
result /= 10;
}

}
``````

cpp version

``````class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *dummy = new ListNode(0), *p = dummy;
int carry = 0;
while(l1 || l2 || carry) {
if(l1) {
carry+=l1->val;
l1 = l1->next;
}
if(l2) {
carry+=l2->val;
l2 = l2->next;
}
p->next = new ListNode(carry%10);
carry /= 10;
p = p->next;
}
return dummy->next;
}
};
``````