LeetCode002

传送门

/** * 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) {
          ListNode *nl=NULL,*cr=NULL;
       int carry=0;
       while(l1!=nullptr || l2!=nullptr){
          if(l1!=nullptr){
            carry+=l1->val;
            l1=l1->next;
          }
          if(l2!=nullptr){
            carry+=l2->val;
            l2=l2->next;
          }
          //first time
          if(nl==NULL){
            nl=new ListNode(carry%10);
            cr=nl;
          }else
          {
            ListNode *temp=new ListNode(carry%10);
            nl->next=temp;
            nl=nl->next;
          }
          carry/=10;
       }
       if(carry==1)
            nl->next=new ListNode(carry);
       return cr;
    }
};

你可能感兴趣的:(LeetCode)