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
解决代码:
/** * 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 == nullptr) return l2; if(l2 == nullptr) return nullptr; ListNode* temp1 = l1; ListNode* temp2 = l2; ListNode* first1 = l1; ListNode* first2 = l2; int count = 0; while(temp1 != nullptr && temp2 != nullptr) { temp1->val = temp1->val + temp2->val + count; count = temp1->val / 10; temp1->val = temp1->val%10; temp2->val = temp1->val; first1 = temp1; first2 = temp2; temp1 = temp1->next; temp2 = temp2->next; } if(temp2 == nullptr) { while(temp1 != nullptr) { temp1->val = temp1->val + count; count = temp1->val / 10; temp1->val = temp1->val%10; if(count == 0) return l1; first1 = temp1; temp1 = temp1->next; } if(count != 0) { ListNode* temp = new ListNode(count); first1->next = temp; } return l1; } if(temp1 == nullptr) { while(temp2 != nullptr) { temp2->val = temp2->val + count; count = temp2->val / 10; temp2->val = temp2->val%10; if(count == 0) return l2; first2 = temp2; temp2 = temp2->next; } if(count != 0) { ListNode* temp = new ListNode(count); first2->next = temp; } return l2; } } };
原文地址:http://blog.csdn.net/shaya118/article/details/42499191