
这道题还是有点难度, 需要维护一个进位值,构造一个虚拟头节点dummy,用于结果的返回,还要构造一个当前节点cur,用于遍历修改新链表。
整体思路就是长度短的链表需要补0,然后两链表从头开始遍历相加(要考虑进位)。
需要注意的点有:补0操作、考虑进位、最后遍历完之后还要再判断一下进位值,如果大于0得话还需要添加一个节点。
代码如下:
- /**
- * 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* dummy = new ListNode(0); //虚拟头节点
- ListNode* cur = dummy;
- int carry = 0; //进位
- while(l1 || l2)
- {
- int n1 = l1 ? l1->val : 0;
- int n2 = l2 ? l2->val : 0;
- int sum = n1 + n2 + carry;
- 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 dummy->next;
- }
- };