knakul853

Untitled

Jul 16th, 2020
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 0 0
  1. /**
  2. knakul853
  3.  */
  4. class Solution {
  5. public:
  6.     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
  7.        
  8.       ListNode *p=l1;
  9.       ListNode *q = l2;
  10.       ListNode *ans = new ListNode(0);
  11.       ListNode *curr = ans;
  12.         int carry=0;
  13.     while(p!=NULL || q!=NULL)
  14.     {
  15.         int n1 = p!=NULL?p->val:0;
  16.         int n2 = q!=NULL?q->val:0;
  17.         int sm = n1 + n2 +  carry;
  18.         carry=sm/10;
  19.         curr->next = new ListNode(sm%10);
  20.         curr = curr->next;
  21.         if(p!=NULL)p=p->next;
  22.         if(q!=NULL)q=q->next;
  23.        
  24.     }
  25.         if(carry){
  26.             curr->next=new ListNode(carry);
  27.             curr=curr->next;        
  28.     }
  29.         return ans->next;
  30.      
  31.        
  32.          
  33.        
  34.     }
  35. };
Add Comment
Please, Sign In to add comment