Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Code:
class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode *start= new ListNode(0); start->next=l1; while(l1||l2){ if(l1&&l2){ l1->val=l1->val+l2->val; if(l1->val>9){ l1->val=l1->val%10; if(l1->next) l1->next->val=l1->next->val+1; else if(l2->next){ l1->next=l2->next; l2->next->val=l2->next->val+1; l2=NULL; }else{ ListNode *carry= new ListNode(1); l1->next=carry; } } if(!l1->next&&l2->next){ l1->next=l2->next; l2=NULL; } l1=l1->next; if(l2) l2=l2->next; }else if(l1){ if(l1->val>9){ l1->val=l1->val%10; if(l1->next) l1->next->val=l1->next->val+1; else{ ListNode *carry= new ListNode(1); l1->next=carry; } } l1=l1->next; } } l1=start->next; delete start; return l1; } };