2.Add Two Num

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head = new ListNode(1);
        ListNode *tail = head;
        int sum,temp;
        temp = 0;
        while(l1!=nullptr || l2!=nullptr || temp!=0){
            sum=0;
            if(l1!=nullptr){
                sum+=l1->val;
                l1 = l1->next;
            }
            if(l2!=nullptr){
                sum+=l2->val;
                l2 = l2->next;
            }
            int val;
            if(temp == 0){
                val = sum;
                temp = val/10;
                val=sum%10;
            } 
            else{
                val = sum+temp;
                temp = val/10;
                val = val%10;
            } 
            ListNode *node = new ListNode(val);
            tail->next = node;
            tail = tail->next;
        }
          
        return head->next;
    }

你可能感兴趣的:(2.Add Two Num)