Advertisement
SalmaYasser

Untitled

Dec 5th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 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.  
  14. ListNode* x = new ListNode(0);
  15. ListNode* curr = x;
  16. ListNode* h1 = l1;
  17. ListNode* h2 = l2;
  18.  
  19. int c = 0;
  20. while(h1 || h2 || c )
  21. {
  22. if (h1)
  23. {
  24. c += h1->val;
  25. h1 = h1->next;
  26. }
  27.  
  28. if (h2)
  29. {
  30. c += h2->val;
  31. h2 = h2->next;
  32. }
  33. curr -> next = new ListNode( c % 10 );
  34. curr = curr -> next;
  35. c /= 10;
  36. }
  37.  
  38. x = x -> next;
  39. return x;
  40.  
  41.  
  42. }
  43. };
  44.  
  45. /*
  46. 342 + 465 = 807.
  47.  
  48. 3 4 2
  49. 4 6 5
  50. -------
  51. 7 0 8
  52.  
  53. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement