剑指 Offer II 025. 链表中的两数相加 mid
给定两个 非空链表 l1和 l2来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
可以假设除了数字 0之外,这两个数字都不会以零开头。

输入:l1 = [7,2,4,3], l2 = [5,6,4]
输出:[7,8,0,7]
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[8,0,7]
输入:l1 = [0], l2 = [0]
输出:[0]
0解法一:反正链表 模拟加法
如图,以下两个链表做加法 [7 , 2 , 4 , 3]和 [5 , 6 , 4]。

我们一般模拟加法都是 从最低位 开始相加,也就是需要把链表倒过来。

模拟加法。

最后再将结果链表反转过来,就是答案 [ 7 , 8 , 0 , 7]。

链表如何反转
时间复杂度: O(n)O(n)O(n)
代码:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* reverse(ListNode* head){ListNode *cur = head , *pre = nullptr;while(cur != nullptr){ListNode* nextNode = cur->next;cur->next = pre;pre = cur;cur = nextNode;}return pre;}ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode *a = reverse(l1) , *b = reverse(l2);ListNode* dummy = new ListNode(-1);ListNode* pre = dummy;int ca = 0;while(a != nullptr || b != nullptr || ca){int sum = ca;if(a != nullptr){sum += a->val;a = a->next;}if(b != nullptr){sum += b->val;b = b->next;}ListNode *node = new ListNode(sum%10);pre->next = node;pre = node;ca = sum / 10;}return reverse(dummy->next);}
};
解法二:栈 模拟加法
又有题目要求 我们不能改变原链表的结构。所以,我们可以用两个 栈stack来分别存储两个链表的节点值,接着再来模拟加法。
时间复杂度: O(n)O(n)O(n)
代码:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* reverse(ListNode *head){ListNode *pre = nullptr;ListNode *cur = head;while(cur){ListNode *nextNode = cur->next;cur->next = pre;pre = cur;cur = nextNode;}return pre;}ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {stack a,b;while(l1 != nullptr){a.push(l1->val);l1 = l1->next;}while(l2 != nullptr){b.push(l2->val);l2 = l2->next;}ListNode *dummy = new ListNode(-1);ListNode *pre = dummy;int ca = 0;while(!a.empty() || !b.empty() || ca){int sum = ca;if(!a.empty()){sum += a.top();a.pop();}if(!b.empty()){sum += b.top();b.pop();}ListNode *node = new ListNode(sum % 10);pre->next = node;pre = node;ca = sum / 10;}return reverse(dummy->next);}
};