leetcode2_兩數相加_鏈表

1. 用carry來每次更新進位.

2. 考慮特殊情況, [0,1]和[0,1,2], []和[0,1], [1]和[9,9], 即額外的進位.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        //啞結點,初始化返回的鏈表的第一個節點.
        ListNode* dummy = new ListNode(0);
        ListNode* cur = dummy;
        int carry = 0;
        int value1 = 0, value2 = 0;
        while(l1!=NULL || l2!=NULL) {
            //鏈表可能不一樣長.
            value1 = (l1==NULL) ? 0:l1->val;
            value2 = (l2==NULL) ? 0:l2->val;
            int sum = value1+value2+carry;
            carry = sum/10;
            cur->next = new ListNode(sum%10);
            cur = cur->next;
            if(l1!=NULL) l1 = l1->next;
            if(l2!=NULL) l2 = l2->next;
        }
        //鏈表最後可能有進位.
        if(carry>0) cur->next = new ListNode(carry);
        return dummy->next; 
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章