参考代码 | /**
* 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* result = NULL;
vector<int> v1, v2;
v1.clear();
v2.clear();
v1.push_back(0);
v2.push_back(0);
while(l1 != NULL) {
v1.push_back(l1->val);
l1 = l1->next;
}
while(l2 != NULL) {
v2.push_back(l2->val);
l2 = l2->next;
}
int len1 = v1.size(), len2 = v2.size();
int length = min(len1-1, len2-1);
if(len1 >= len2) {
for(int i=1; i<=length; i++) {
v1[len1-i] = v1[len1-i]+v2[len2-i];
if(v1[len1-i] >= 10) {
v1[len1-i] -= 10;
v1[len1-i-1] ++;
}
}
for(int i=len1-length-1; i>=1; i--) {
if(v1[i] >= 10) {
v1[i] -= 10;
v1[i-1] ++;
}
}
ListNode* temp;
if(v1[0] != 0) {
temp = new ListNode(v1[0]);
result = temp;
}
for(int i=1; i<len1; i++) {
if(NULL == result) {
temp = new ListNode(v1[i]);
result = temp;
} else {
temp->next = new ListNode(v1[i]);
temp = temp->next;
}
}
} else{
for(int i=1; i<=length; i++) {
v2[len2-i] = v1[len1-i]+v2[len2-i];
if(v2[len2-i] >= 10) {
v2[len2-i] -= 10;
v2[len2-i-1] ++;
}
}
for(int i=len2-length-1; i>=1; i--) {
if(v2[i] >= 10) {
v2[i] -= 10;
v2[i-1] ++;
}
}
ListNode* temp;
if(v2[0] != 0) {
temp = new ListNode(v2[0]);
result = temp;
}
for(int i=1; i<len2; i++) {
if(NULL == result) {
temp = new ListNode(v2[i]);
result = temp;
} else {
temp->next = new ListNode(v2[i]);
temp = temp->next;
}
}
}
return result;
}
};
|