[Leetcode] (Add two numbers daily)

Insert picture description here
After reading the question for a long time, I understood what it meant. In the end, I could only look at the solution of the selected question.
Insert picture description here

class Solution {
    
    
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
    
        ListNode* head=new ListNode(-1);//存放结果的链表
        ListNode* h=head;//移动指针
        int sum=0;//每个位的加和结果
        bool carry=false;//进位标志
        while(l1!=NULL||l2!=NULL)
        {
    
    
            sum=0;
            if(l1!=NULL)
            {
    
    
                sum+=l1->val;
                l1=l1->next;
            }
            if(l2!=NULL)
            {
    
    
                sum+=l2->val;
                l2=l2->next;
            }
            if(carry)
                sum++;
            h->next=new ListNode(sum%10);
            h=h->next;
            carry=sum>=10?true:false;
        }
        if(carry)
        {
    
    
            h->next=new ListNode(1);
        }
        return head->next;
    }
};


Guess you like

Origin blog.csdn.net/qq_45657288/article/details/108918249