Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode(int x) : val(x), next(NULL) {}
  7.  * };
  8.  */
  9. class Solution {
  10. public:
  11.     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
  12.        
  13.         /* new ListNode to store sum,
  14.             the first element is a dummy node which we will discard */
  15.         ListNode* sum = new ListNode(-1);
  16.        
  17.         // pointers to traverse the 3 lists
  18.         ListNode* p1 = l1;
  19.         ListNode* p2 = l2;
  20.         ListNode* p3 = sum;
  21.        
  22.         // carry over to next digit
  23.         int carry = 0;
  24.        
  25.         /* loop until both summands no longer have digits remaining
  26.             and there is no carry remaining */
  27.         while (p1 != NULL || p2 != NULL || carry > 0){
  28.            
  29.             // add up the two digits and the carry digit
  30.             int curr = carry;
  31.             carry = 0;
  32.            
  33.             if (p1 != NULL){
  34.                 curr += p1->val;
  35.                 p1 = p1->next;
  36.             }
  37.             if (p2 != NULL){
  38.                 curr += p2->val;
  39.                 p2 = p2->next;
  40.             }
  41.            
  42.             // check for carry
  43.             if (curr > 9){
  44.                 curr -= 10;
  45.                 carry = 1;
  46.             }
  47.  
  48.             // set next node to computed digit
  49.             ListNode* temp = new ListNode(curr);
  50.             p3->next = temp;
  51.             p3 = p3->next;
  52.         }
  53.        
  54.         // return discarding the first -1 dummy node
  55.         return sum->next;        
  56.     }
  57. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement