【leetcode】(每日抑题 2 两数相加)

在这里插入图片描述
题目看了半天才明白啥意思,最后还是只能看精选题解里的
在这里插入图片描述

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;
    }
};


猜你喜欢

转载自blog.csdn.net/qq_45657288/article/details/108918249