【链表】Leetcode 两数相加-算法讲解

时间:2024-04-26 07:36:36

我们这里设置一个头结点,然后遍历两个链表,使用一个flag记录相加的结果和进位,如果两个链表没有走到最后或者进位不等于0,我们就继续遍历处理进位;如果当前的链表都遍历完成了,判断当前的进位是否>10,然后处理是否需要添加进位结点

/**
 * 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* newhead = new ListNode(-1);
        ListNode* pthread = newhead;
        ListNode* cur1 = l1;
        ListNode* cur2 = l2;
        int flag = 0;
        while(cur1 || cur2 || flag)
        {
            if(cur1)
            {
                flag += cur1->val;
                cur1 = cur1->next;
            }
            if(cur2)
            {
                flag += cur2->val;
                cur2 = cur2->next;
            }
            ListNode*node = new ListNode(flag % 10);
            flag /= 10;
            pthread->next = node;
            pthread = node;
        }
        pthread = newhead ->next;
        delete newhead;
        return pthread; 
    }
};