LikeRampage

Chatgpt v5.1 and v5.0 C++ 445. Add Two Numbers II

Feb 16th, 2026
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. Here is one of the interview-favorite solutions: do the addition on-the-fly while you are popping the stacks that were built from the two lists.  
  2. No reversing the lists, no extra O(n) recursion, no dummy node; just two stacks and a carry.
  3.  
  4. ```cpp
  5. #include <stack>
  6.  
  7. struct ListNode {
  8.     int val;
  9.     ListNode *next;
  10.     ListNode() : val(0), next(nullptr) {}
  11.     explicit ListNode(int x) : val(x), next(nullptr) {}
  12.     ListNode(int x, ListNode *n) : val(x), next(n) {}
  13. };
  14.  
  15. class Solution {
  16. public:
  17.     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
  18.         std::stack<int> s1, s2;
  19.  
  20.         // push every digit into its own stack (MSB on top)
  21.         for (; l1; l1 = l1->next) s1.push(l1->val);
  22.         for (; l2; l2 = l2->next) s2.push(l2->val);
  23.  
  24.         ListNode *res = nullptr;   // head of the result list we are building
  25.         int carry = 0;
  26.  
  27.         while (!s1.empty() || !s2.empty() || carry) {
  28.             int a = s1.empty() ? 0 : s1.top(), b = s2.empty() ? 0 : s2.top();
  29.             if (!s1.empty()) s1.pop();
  30.             if (!s2.empty()) s2.pop();
  31.  
  32.             int sum = a + b + carry;
  33.             carry = sum / 10;
  34.  
  35.             // prepend the new digit node
  36.             auto *node = new ListNode(sum % 10);
  37.             node->next = res;
  38.             res = node;
  39.         }
  40.         return res;
  41.     }
  42. };
  43. ```
  44.  
  45. Complexities  
  46. - Time: O(n + m) – each node is pushed and popped once.  
  47. - Extra space: O(n + m) – the two stacks (you can shrink it to O(1) by reversing the lists in-place if you want).
Tags: C++ leetcode
Advertisement
Add Comment
Please, Sign In to add comment