Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

  /* *
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 
*/
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
         if(l2==NULL)  return l1;
         if(l1==NULL)  return l2;
            
         struct ListNode * head=NULL;
        
         // copy l1
         struct ListNode * current=NULL;
         while(l1!=NULL)
        {
             struct ListNode * newNode= new  struct ListNode(l1->val);
             if(head==NULL)
                head=newNode;
             else
                current->next=newNode;
            current=newNode;
            l1=l1->next;
        }
         // add
         struct ListNode * p1=head;
         struct ListNode * p2=l2;
         int add= 0;
         while( true)
        {
             int sum;
             if(p2!=NULL)
                sum=p1->val+p2->val+add;
             else
                sum=p1->val+add;
            p1->val=sum>= 10?sum- 10:sum;
            add=sum>= 10? 1: 0;
            
             if(p1->next==NULL && p2==NULL && add== 0)
                 break;
             if(p1->next==NULL && p2!=NULL && p2->next==NULL && add== 0)
                 break;
                
             if(p1->next==NULL)
                p1->next= new  struct ListNode( 0);
            p1=p1->next;
             if(p2!=NULL) 
                p2=p2->next;
        }
     
         return head;
    }
};

你可能感兴趣的:(number)