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
Solution:
Add each element of two list with the help of a variable "carry". When both of the lists meet their end, return result.
1. One of the list is NULL:
l1: NULL
l2: 1->2
sum: 1->2
2. The lengths of l1 and l2 are different:
l1: 2->2
l2: 9->9->9
sum: 1->2->0->1
Coding(C++):
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* res = new ListNode(0); ListNode* head = res; int carry = 0; while(l1 && l2){ res->next = new ListNode((l1->val+l2->val+carry)%10); res = res->next; carry = (l1->val+l2->val+carry)/10; l1 = l1->next; l2 = l2->next; } while(l1){ res->next = new ListNode((l1->val+carry)%10); res = res->next; carry = (l1->val+carry)/10; l1 = l1->next; } while(l2){ res->next = new ListNode((l2->val+carry)%10); res = res->next; carry = (l2->val+carry)/10; l2 = l2->next; } if(carry > 0){ res->next = new ListNode(carry); } return head->next; } };
No comments :
Post a Comment