Advertisement
nikunjsoni

2

Mar 19th, 2021
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
  14.         ListNode *dummy = new ListNode(0);
  15.         ListNode *res = dummy;
  16.         int carry = 0;
  17.        
  18.         while(l1 || l2 || carry){
  19.             int sum = carry;
  20.             if(l1) sum += l1->val, l1 = l1->next;
  21.             if(l2) sum += l2->val, l2 = l2->next;
  22.             res->next = new ListNode(sum%10);
  23.             carry = sum /= 10;
  24.             res = res->next;
  25.         }
  26.         return dummy->next;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement