classSolution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){ stack<int> s1, s2; while (l1) { s1.push(l1 -> val); l1 = l1 -> next; } while (l2) { s2.push(l2 -> val); l2 = l2 -> next; } int carry = 0; ListNode* ans = nullptr; while (!s1.empty() or !s2.empty() or carry != 0) { int a = s1.empty() ? 0 : s1.top(); int b = s2.empty() ? 0 : s2.top(); if (!s1.empty()) s1.pop(); if (!s2.empty()) s2.pop(); int cur = a + b + carry; carry = cur / 10; cur %= 10; auto curnode = newListNode(cur); curnode -> next = ans; ans = curnode; } return ans; } };
classSolution: defaddTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: s1, s2 = [], [] while l1: s1.append(l1.val) l1 = l1.next while l2: s2.append(l2.val) l2 = l2.next ans = None carry = 0 while s1 or s2 or carry != 0: a = 0ifnot s1 else s1.pop() b = 0ifnot s2 else s2.pop() cur = a + b + carry carry = cur // 10 cur %= 10 curnode = ListNode(cur) curnode.next = ans ans = curnode return ans