Problem:
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.
Solution:
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int carry = 0;
ListNode *sol = NULL;
ListNode *temp = NULL;
while (l1 != NULL || l2 != NULL) {
int sum = (l1 != NULL ? l1->val : 0) + (l2 != NULL ? l2->val : 0) + carry;
carry = sum/10;
ListNode *node = new ListNode(sum % 10);
if (sol == NULL) {
sol = node;
temp = sol;
}
else {
temp->next = node;
temp = temp->next;
}
l1 = (l1 != NULL ? l1->next : NULL);
l2 = (l2 != NULL ? l2->next : NULL);
}
if (l1 == NULL && l2 == NULL && carry) {
ListNode *node = new ListNode(carry);
temp->next = node;
}
return sol;
}
};
No comments:
Post a Comment