一緒にLeetCode--二つの数字

2つの数値


 //* 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) {
          
          int lastAddpro = 0;
          ListNode *ListNodeAdd = new ListNode(0);
          ListNode *Head = ListNodeAdd;
          ListNodeAdd->val = (l1->val + l2->val)%10;
          lastAddpro = (l1->val + l2->val)/10;
          l1=l1->next; l2=l2->next;
          while(l1 != NULL || l2 !=NULL)
          {
              ListNode *structListNodeCur = new ListNode(0);
              
              if(l1==NULL)
              {
                  structListNodeCur->val = (l2->val + lastAddpro)%10;
                  lastAddpro = (l2->val + lastAddpro)/10;
                  l2=l2->next;
              } 
              else if(l2==NULL)
              {
                  structListNodeCur->val = (l1->val + lastAddpro)%10;
                  lastAddpro = (l1->val + lastAddpro)/10;
                  l1=l1->next; 
              }
              else
              {
                   structListNodeCur->val = (l1->val + l2->val + lastAddpro)%10;
                   lastAddpro = (l1->val + l2->val + lastAddpro)/10;
                   l1=l1->next; l2=l2->next;
              }
              ListNodeAdd->next = structListNodeCur;
              ListNodeAdd = structListNodeCur;
          }  
          if(lastAddpro>0)
          {
             ListNode *structListNodeCur = new ListNode(0);
             structListNodeCur->val = lastAddpro;
             ListNodeAdd->next = structListNodeCur;       
          } 
        return Head;  
    }
};
41元記事公開 ウォン称賛85 ビューに25万+を

おすすめ

転載: blog.csdn.net/zhoucoolqi/article/details/103341000