给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> h_1;
stack<int> h_2;
while(l1 != NULL){
h_1.push(l1->val);
l1 = l1->next;
}
while(l2 != NULL){
h_2.push(l2->val);
l2 = l2->next;
}
int length = max(h_1.size(), h_2.size());
ListNode* res = new ListNode(0);
ListNode* head = res;
int flag = 0;
while(!h_1.empty() || !h_2.empty()){
int value;
if(!h_1.empty() && !h_2.empty()){
value = (h_1.top() + h_2.top() + flag) % 10;
flag = (h_1.top() + h_2.top() + flag) / 10;
h_1.pop();
h_2.pop();
}else if(!h_1.empty()){
value = (h_1.top() + flag) % 10;
flag = (h_1.top() + flag) / 10;
h_1.pop();
}else{
value = (h_2.top() + flag) % 10;
flag = (h_2.top() + flag) / 10;
h_2.pop();
}
ListNode* next = new ListNode(value);
res->next = next;
res = res->next;
}
if(flag > 0){
ListNode* next = new ListNode(flag);
res->next = next;
res = res->next;
}
ListNode* pre = NULL;
ListNode* cur = head->next;
while(cur != NULL){
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。