美文网首页
2.Add Two Num

2.Add Two Num

作者: 林里icer | 来源:发表于2018-03-24 21:43 被阅读0次
    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

          本文链接:https://www.haomeiwen.com/subject/iteccftx.html