LeetCode/solutions/2. Add Two Numbers.md

1.7 KiB
Raw Blame History

2. Add Two Numbers

思路

从前到尾不断将两个链表的元素相加就行了这个过程中一直会用到一个代表进位的变量cin另外注意处理两个链表不等长的情况。

C++

class Solution {
private:
    int digit_add(const int a, const int b, int& cin){ // 先定义一个一位数字相加的函数方便后面使用注意是用引用的方式传入cin的
        int sum = a + b + cin;
        cin = sum / 10;
        return sum % 10;
    }
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int cin = 0; // 进位
        ListNode *root = new ListNode(digit_add(l1 -> val, l2 -> val, cin)); // root是最后要返回的指针
        ListNode *last = root; // last指向当前结果链表中的最后一个元素
        l1 = l1 -> next;
        l2 = l2 -> next;
        while(l1 && l2){  // 由前先后对两个链表的元素相加
            last -> next = new ListNode(digit_add(l1 -> val, l2 -> val, cin));
            last = last -> next;
            l1 = l1 -> next;
            l2 = l2 -> next;
        }
        if(l2) l1 = l2; // 若l2长一些将l1指向l2后续就只对l1处理就行了.
        while(l1 && cin > 0){
            last -> next = new ListNode(digit_add(l1 -> val, 0, cin));
            last = last -> next;
            l1 = l1 -> next;
        }
        if(l1) last -> next = l1; // cin = 0直接将l1后续的所有节点接到last后面就行了
        else{   // l1 == NULL cin >= 0
            if(cin > 0){
                last -> next = new ListNode(cin);
                last = last -> next;    
            }
            last -> next = NULL;
        }
        return root;
    }
};