题目链接 模拟两数相加,记录进位。
/** * 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 = new ListNode(-1); ListNode* cur = head; int t = 0, L, R; while (l1 || l2 || t) { L = l1 ? l1->val : 0; R = l2 ? l2->val : 0; int num = t + L + R; t = num / 10; num %= 10; ListNode* now = new ListNode(num); cur->next = now; cur = now; if (l1) l1 = l1->next; if (l2) l2 = l2->next; } return head->next; } };