我自己做的网站上有图片宣传食品,网页设计平面设计哪个好,网站流量怎么做,池州网站建设价格2023.9.14 这道题还是有点难度#xff0c; 需要维护一个进位值#xff0c;构造一个虚拟头节点dummy#xff0c;用于结果的返回#xff0c;还要构造一个当前节点cur#xff0c;用于遍历修改新链表。 整体思路就是长度短的链表需要补0#xff0c;然后两链表从头开始遍历相加…2023.9.14 这道题还是有点难度 需要维护一个进位值构造一个虚拟头节点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;}
};