[CPP]32ms C++ Solution


  • 0
    Z

    '''
    /**

    • 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 c = 0;
      ListNode *t1 = l1,*t2 = l2,*pre;
      while(t1 != NULL && t2 != NULL)
      {
      t1->val += t2->val + c;
      if (t1->val >= 10)
      {
      c = t1->val / 10;
      t1->val %= 10;
      }
      else
      c = 0;
      pre = t1;
      t1 = t1 -> next;
      t2 = t2 -> next;
      }
      while(t1 != NULL)
      {
      t1->val += c;
      if(t1->val >= 10)
      {
      c = t1->val / 10;
      t1->val %= 10;
      }
      else
      c = 0;
      pre = t1;
      t1 = t1->next;
      }
      while(t2 != NULL)
      {
      if(t1 == NULL) t1 = new ListNode(c);
      t1->val += t2->val;
      if(t1->val >= 10)
      {
      c = t1->val /10;
      t1->val %= 10;
      }
      else
      c = 0;
      pre->next = t1;
      pre = t1;
      t1 = t1 -> next;
      t2 = t2 -> next;
      }
      if(c)
      {
      t1 = new ListNode(c);
      pre->next = t1;
      }
      return l1;
      }
      };
      '''

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.