Add Two Numbers

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int convert(ListNode* t)
    {
        if(t!=NULL)
            return t->val;
        else
            return 0;
    }
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
       ListNode* res=new ListNode((convert(l1)+convert(l2))%10);
       ListNode* temp1=l1;
       ListNode* temp2=l2;
       ListNode* temp=res;
       int y=(convert(l1)+convert(l2))/10;
       int v;
       int q1,q2;
       bool f1=1,f2=1;
       while(1)
       {
           
           if(f1)
           {
               if(temp1->next==NULL)
               {
                   q1=0;
                   f1=0;
               }
               else
                   q1=temp1->next->val;
           }
            if(f2)
           {
               if(temp2->next==NULL)
               {
                   q2=0;
                   f2=0;
               }
               else
                   q2=temp2->next->val;
           }
           if(f1==0&&f2==0)
               break;
           v=q1+q2+y;
           temp->next=new ListNode(v%10);
           y=v/10;
           temp=temp->next;
           if(f1!=0)
           temp1=temp1->next;
           if(f2!=0)
           temp2=temp2->next;
       }
       if(y!=0)
           temp->next=new ListNode(y);
       return res;
    }
    };

  

原文地址:https://www.cnblogs.com/xlqtlhx/p/7862011.html