Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 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.  
  12. ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
  13. ListNode* root = new ListNode(0);
  14. ListNode* node = root;
  15. int carry = 0;
  16. while (l1 || l2)
  17. {
  18. int n1 = l1 ? l1->val : 0;
  19. int n2 = l2 ? l2->val : 0;
  20. int sum = n1 + n2 + carry;
  21. carry = sum / 10;
  22.  
  23. node->next = new ListNode(sum % 10);
  24. node = node->next;
  25.  
  26. if (l1) l1 = l1->next;
  27. if (l2) l2 = l2->next;
  28. }
  29.  
  30. if (carry > 0)
  31. {
  32. node->next = new ListNode(carry);
  33. }
  34.  
  35. return root->next;
  36. }
  37. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement