Add two numbers represented as linked List :
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
/*
* 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) {
if (!l1)
return l2;
if (!l2)
return l1;
int sum = 0, carry = 0;
ListNode* head1 = reverse(l1);
ListNode* head2 = reverse(l2);
ListNode* result = NULL;
ListNode* temp = NULL;
while (head1 || head2 || carry) {
int v1 = !head1 ? 0 : head1->val;
int v2 = !head2 ? 0 : head2->val;
sum = v1 + v2;
temp = new ListNode((sum + carry) % 10);
temp->next = result;
result = temp;
carry = (sum + carry) / 10;
head1 = !head1? NULL : head1->next;
head2 = !head2? NULL : head2->next;
}
return result;
}
ListNode* reverse(ListNode* head) {
if (!head) return NULL;
ListNode* newHead = NULL;
ListNode* next = NULL;
while (head) {
next = head->next;
head->next = newHead;
newHead = head;
head = next;
}
return newHead;
}
};
No comments:
Post a Comment