/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *res = NULL, *prep = NULL, *ptr = NULL;
ListNode *p1 = l1, *p2 = l2;
res = newListNode(0);
prep = ptr = res;
int curNum, nextNum;
curNum = nextNum = 0;
while(p1 != NULL && p2 != NULL){
curNum += p1->val + p2->val;
nextNum += curNum / 10;
curNum %= 10;
ptr->val = curNum;
ptr->next = newListNode(0);

curNum = nextNum;
nextNum = 0;
p1 = p1->next;
p2 = p2->next;
prep = ptr;
ptr = ptr->next;
}
ListNode* tmp;
if(p1 == NULL){
tmp = p2;
}
else{
tmp = p1;
}
while(tmp != NULL){
curNum += tmp->val;
nextNum = curNum / 10;
curNum %= 10;

ptr->val = curNum;
ptr->next = newListNode(0);

prep = ptr;
ptr = ptr->next;
curNum = nextNum;
tmp = tmp->next;
}
if(curNum != 0){
ptr->val = curNum;
ptr->next = NULL;
}
else{
prep->next = NULL;
//free(ptr);
}
return res;
}
private:
ListNode* newListNode(int num){
ListNode* tmp = new ListNode(num);
return tmp;
}
};

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客