解题思路:
- 模拟,分别便利两个数组,将数字提取出来,再相加,最后得出的数字再转化为链表
- 创建链表,算一个建一个结点,指针向后遍历一位,模拟十进制算法即可
代码:
/**
* 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* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = nullptr, *tail = nullptr;
int carry = 0;
while (l1 != nullptr || l2 != nullptr) { // 直到两个链表都结束了
int n1 = l1 ? l1->val: 0; // l1链表空了就赋值0
int n2 = l2 ? l2->val: 0; // l2一样。
int sum = n1 + n2 + carry;
if (!head) { // 还未有结点时
head = tail = new ListNode(sum % 10);
} else {
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
carry = sum / 10; // 获取进位
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
if (carry >= 1) {
tail->next = new ListNode(carry);
}
return head;
}
};