WEI-CHENG CHEN

說明

  1. 給兩個 linklist,去做加法
  2. 加完結果作顛倒

解法:模擬

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        // 加總結果的linklist
        ListNode *head=nullptr, *tail = nullptr;
        int carry = 0;
        while(l1 || l2){
            // 取出l1 l2各自的值
            int n1 = 0, n2 = 0;
            if(l1) n1 = l1->val;
            if(l2) n2 = l2->val;

            int sum = carry + n1 + n2;

            // 串到新linklist
            if(!head){
                head = new ListNode(sum%10);
                tail = head;
            }else{
                tail->next = new ListNode(sum%10);
                tail = tail->next;
            }

            carry = sum/10;

            if(l1)l1 = l1->next;
            if(l2)l2 = l2->next;

        }
        // 做最後檢查,查看看是否還有數值
        if(carry){
            tail->next = new ListNode(carry);
            tail = tail->next;
        }
        return head;
    }
};