jayati

Add Two Numbers

Sep 21st, 2022
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 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* temp = new ListNode();
  15. ListNode* curr = temp;
  16. int carry=0;
  17. while(l1!= NULL || l2!=NULL || carry!=0)
  18. {
  19. int x,y;
  20. if(l1)
  21. {
  22. x=l1->val;
  23. }
  24. else
  25. {
  26. x=0;
  27. }
  28. if(l2)
  29. {
  30. y=l2->val;
  31. }
  32. else
  33. {
  34. y=0;
  35. }
  36. int ans=x+y+carry;
  37. carry=ans/10;
  38. curr->next=new ListNode(ans%10);
  39. curr=curr->next;
  40. l1=l1?l1->next:nullptr;
  41. l2=l2?l2->next:nullptr;
  42. }
  43.  
  44. return temp->next;
  45. }
  46. };
Advertisement
Add Comment
Please, Sign In to add comment