Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
1.3 kB
1
Indexable
Never
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* result,*current,*ln1=l1,*ln2=l2;
        int carrier = 0,sum=0;
        current = result;
        while (ln1 != nullptr || ln2 !=nullptr || carrier != 0){
            ListNode* resNext;
            if(ln1 != nullptr && ln2!= nullptr){
                sum = ln1->val + ln2->val+carrier;    
            }
            else if (ln1 == nullptr && ln2== nullptr) sum = carrier;
            else if  (ln1 == nullptr ){
                sum = ln2->val+carrier;    
            }
            else{
                sum = ln1->val + carrier;    
            }
            carrier = sum/10;
            current->val = sum%10;
            current->next = resNext;
            current = resNext;
            
        }
        ListNode* dummy = result;
        while(dummy != nullptr){
            cout<<dummy->val<<endl;
            dummy = dummy->next;
        }
        return result;
    }
};