/** * 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) { int cur = 0; int res = 0; ListNode* H = new ListNode(); ListNode* L = H; int temp = 0; while(l1||l2){ // 避免两个链表不一样长的情况 if(!l1) temp = l2->val; else if(!l2) temp = l1->val; else temp = l1->val+l2->val; cur = (temp + res)%10; // 求当前位 res = (temp+res)/10; // 求进位 ListNode* p = new ListNode(cur); H->next = p; H = H->next; if(l1) l1 = l1->next; if(l2) l2 = l2->next; } if(res>0) H->next = new ListNode(res); // 如果最后一位进位大于0,则添加 return L->next; } };