1 链表加和 考虑进位 短链表补零
代码语言:javascript复制/**
* 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) {
auto prehead = new ListNode();
auto pre = prehead;
// 进位
int plus = 0;
while (l1 || l2) {
int sum = 0; // 同1位下l1和l2的加和
if (l1) { // 若当前l1不为空,则sum加上当前l1节点的值
sum = l1->val;
l1 = l1->next;
}
if (l2) {
sum = l2->val;
l2 = l2->next;
}
// 若l1和l2节点 上1位进位加和>10
if (sum plus >= 10) {
pre->next = new ListNode(sum plus - 10);
plus = 1;
} else {
pre->next = new ListNode(sum plus);
plus = 0;
}
pre = pre->next;
}
// 考虑最后1位加和可能产生的进位
if (plus == 1) pre->next = new ListNode(1);
return prehead->next;
}
};