[LeetCode] Add Two Numbers

鏈表的操作,修改了好多次,進位等小問題比較多。

/**
 * 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) {
        if (l1 == NULL && l2 == NULL) {
            return NULL;
        }

        int add = 0;
        ListNode *head = new ListNode(0);
        ListNode *current = head;
        while (l1 != NULL || l2 != NULL || add != 0) {
            int sum = 0;
            if (l1 != NULL) {
                sum += l1->val;
                l1 = l1->next;
            }
            if (l2 != NULL) {
                sum += l2->val;
                l2 = l2->next;
            }
            sum += add;
            current->val = sum % 10;
            add = sum / 10;

            if (l1 != NULL || l2 != NULL || add != 0) {
                current->next = new ListNode(0);
                current = current->next;
            }
        }
        return head;        
    }
};


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