Easy C++ solution by comprehend

• The main solution is reverse the single-linked list.

``````class Solution {
public:
ListNode* reverseList(ListNode* head, int& len) {
return NULL;
}
len = 1;
ListNode* pNext = pPrev -> next;
pPrev->next = NULL;
while (pNext != NULL) {
len++;
ListNode* pTemp = pNext->next;
pNext->next = pPrev;
pPrev = pNext;
pNext = pTemp;
}
return pPrev;
}

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int len1 = 0;
int len2 = 0;
ListNode* p1 = reverseList(l1, len1);
ListNode* p2 = reverseList(l2, len2);
ListNode* pSum = NULL;
ListNode* pResult = len1 >= len2 ? p1: p2;
ListNode* pMiddle = NULL;
while (p1 != NULL && p2 != NULL) {
pSum = len1 >= len2 ? p1: p2;
if ((p1->val + p2->val) >= 10) {
pSum->val = (p1->val + p2->val) % 10;
if (pSum->next == NULL) {
ListNode* temp = new ListNode(0);
pSum->next = temp;
}
pSum->next->val++;
} else {
pSum->val = p1->val + p2->val;
}
p1 = p1->next;
p2 = p2->next;
pMiddle = pSum->next;
}
while (pMiddle != NULL) {
if (pMiddle->val >= 10) {
pMiddle->val = pMiddle->val % 10;
if (pMiddle->next == NULL) {
ListNode* temp = new ListNode(0);
pMiddle->next = temp;
}
pMiddle->next->val++;
}
pMiddle = pMiddle->next;
}
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.