445.两数相加 II (Medium)*
题目描述*
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个结点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例*
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
进阶*
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的结点进行翻转。
代码*
跟之前的两数相加题不一样,链表是反向的。可以想到用栈实现,先都入栈,然后逐个出栈相加,结果再入栈,最后构造链表(或者结果直接头插法到链表中)。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// 用栈实现先遍历后计算
stack<ListNode*> s1, s2;
while(l1 != nullptr) {
s1.push(l1);
l1 = l1->next;
}
while(l2 != nullptr) {
s2.push(l2);
l2 = l2->next;
}
int flag = 0;
stack<int> s3;
while(!s1.empty() || !s2.empty() || flag == 1){
int num = 0;
if(!s1.empty()) {
num += s1.top()->val;
s1.pop();
}
if(!s2.empty()) {
num += s2.top()->val;
s2.pop();
}
num += flag;
flag = num >= 10 ? 1 : 0;
num = num%10;
s3.push(num);
}
ListNode *head=new ListNode(s3.top());
s3.pop();
ListNode *p=head;
while(!s3.empty()) {
p->next = new ListNode(s3.top());
s3.pop();
p = p->next;
}
return head;
}
};
执行用时:20ms
内存消耗:14.5MB
最后更新: July 23, 2022