//Traverse through list1, derive the length of l1 while(current != NULL){ len1++; current = current->next; } current = l1; //Derive the value of list1 while (current != NULL){ value1.push_back(current->val); current = current -> next; }
current = l2; //Traverse through list2, derive the length of l2 while(current != NULL){ len2++; current = current ->next; } current = l2; //Derive the value of list2 while(current != NULL){ value2.push_back(current->val); current = current->next; }
//value1 int factor = value1.size() -1; for (int i=value1.size()-1; i>=0; i--){ val1 += value1[i] * pow(10,factor); factor--; }
//value2 factor = value2.size() -1; for (int i=value2.size()-1; i>=0; i--){ val2 += value2[i] * pow(10,factor); factor--; } //sum sum = val1 + val2; // head if(sum %10 != 0){ ListNode* newHead = newListNode(sum % 10); sum = sum /10; current = newHead; previous = newHead; head = newHead; } else{ // 0 tail ListNode* newHead = newListNode(0); sum = sum /10; current = newHead; previous = newHead; head = newHead; }
// body while (sum != 0){ ListNode* newNode = newListNode(sum % 10); current = newNode; previous -> next = newNode; previous = newNode; sum = sum /10; }
if (head == nullptr) { head = newListNode(sum); } return head; } };