Advertisement
nikunjsoni

445

Mar 17th, 2021
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 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.         stack<int> num1, num2, ans;
  15.         while(l1){
  16.             num1.push(l1->val);
  17.             l1 = l1->next;
  18.         }
  19.         while(l2){
  20.             num2.push(l2->val);
  21.             l2 = l2->next;
  22.         }
  23.        
  24.         int carry = 0, sum;
  25.         while(!num1.empty() || !num2.empty()){
  26.             sum = 0;
  27.             if(!num1.empty()){
  28.                 sum += num1.top();
  29.                 num1.pop();
  30.             }
  31.             if(!num2.empty()){
  32.                 sum += num2.top();
  33.                 num2.pop();
  34.             }
  35.             sum += carry;
  36.             ans.push(sum%10);
  37.             carry = sum/10;
  38.         }
  39.         while(carry){
  40.             ans.push(carry%10);
  41.             carry /= 10;
  42.         }
  43.        
  44.         ListNode* head = new ListNode();
  45.         ListNode* curr = head;
  46.         while(!ans.empty()){
  47.             curr->next = new ListNode(ans.top());
  48.             curr = curr->next;
  49.             ans.pop();
  50.         }
  51.         return head->next;
  52.     }
  53. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement