2. 两数相加
/**
* 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;
ListNode* cur = head;
int carry = 0;
while(l1 || l2) {
int num1 = l1? l1->val: 0;
int num2 = l2? l2->val: 0;
int sum = num1 + num2 + carry;
if (head == nullptr) {
head = new ListNode(sum % 10);
cur = head;
} else {
cur->next = new ListNode(sum % 10);
cur = cur->next;
}
carry = sum / 10;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
// 最后一位进位
if (carry > 0) cur->next = new ListNode(carry);
return head;
}
};