官方题解
class Solution {
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 = new ListNode(cur);
curnode -> next = ans;
ans = curnode;
}
return ans;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/add-two-numbers-ii/solution/liang-shu-xiang-jia-ii-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
我的解法
- 遍历链表,把各位数字压栈
- 依次取栈顶元素,相加,创建链表节点,加入链表
- 返回新链表头指针
class Solution {
public:
stack<int> getNum(ListNode* head) {
stack<int> num;
while(head != NULL) {
num.push(head->val);
head = head->next;
}
return num;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1->val == 0) return l2;
if(l2->val == 0) return l1;
stack<int> num1 = getNum(l1);
stack<int> num2 = getNum(l2);
ListNode* ptr = NULL;
ListNode* curr;
int carry = 0;
while(!num1.empty() || !num2.empty()) {
int sum;
if(!num1.empty() && !num2.empty()) {
sum = num1.top() + num2.top();
num1.pop();
num2.pop();
}
else if(!num1.empty()) {
sum = num1.top();
num1.pop();
}
else if(!num2.empty()) {
sum = num2.top();
num2.pop();
}
int actual_sum = sum + carry;
curr = new ListNode(actual_sum % 10);
carry = actual_sum / 10;
curr->next = ptr;
ptr = curr;
}
if(carry != 0) {
curr = new ListNode(carry);
curr->next = ptr;
ptr = curr;
}
return ptr;
}
};