LeetCode_Add Two Numbers

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if(l1 == NULL) return l2;

        if(l2 == NULL) return l1;



        std::vector<int> a,b,c;

        while(l1){

          a.push_back(l1->val);

          l1 = l1->next;

        }

        while(l2){

          b.push_back(l2->val);

          l2 = l2->next;

        }



        int i;

        if(a.size() < b.size()){

          c = a;

          a = b;

          b = c;

        }

       

        for(i =0;i <b.size();i++){

          a[i] = a[i] + b[i];

          if(a[i] >= 10)

          {

             a[i] = a[i] -10;

                if(i+1<a.size())

                  a[i+1] += 1;

                else

                  a.push_back(1);

          }

        }

        for(;i<a.size(); i++)

        {

            if(a[i] >= 10)

            {

                a[i] =a[i] - 10;

                if(i+1 < a.size())

                      a[i+1] += 1;

                else

                    a.push_back(1);

                

            }

            

        }

       ListNode *head,*current,*p;

       head = new ListNode(a[0]);

       current = head;

       for(i = 1; i<a.size(); i++){

       

        p = new ListNode(a[i]);

        current->next = p;

        current = p;

       }



      return head;

    }

 

你可能感兴趣的:(LeetCode)