LeetCode - Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

typedef struct ListNode {
    int val;
    ListNode *next;
} ListNode;

bool addNode(ListNode** head, int value) {
    ListNode* node = (ListNode*) malloc(sizeof(ListNode));

    if (NULL == node) {
        return false;
    }

    node->next = NULL;
    node->val = value;

    if (NULL == head) {
        return false;
    }

    if (NULL == *head) {
        *head = node;

        return true;
    }

    //Get the last node
    bool flag = false;
    ListNode* tmp0 = *head;
    ListNode* tmp1 = *head;
    while (tmp1) {
        if (flag) {
            tmp0 = tmp0->next;
        }

        flag = true;
        tmp1 = tmp1->next;
    }

    tmp0->next = node;
    return true;
}

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {

    ListNode* head = NULL;

    if (NULL == l1) {
        return l2;
    }

    if (NULL == l2) {
        return l1;
    }

    bool rt = false;
    int tmpSum = 0;
    ListNode* tmp1 = l1;
    ListNode* tmp2 = l2;
    while (true) {
        if (tmp1 && tmp2) {
            tmpSum += tmp1->val + tmp2->val;
            rt = addNode(&head, tmpSum % 10);

            if (false == rt) {
                return NULL;
            }

            tmpSum = tmpSum / 10;

            tmp1 = tmp1->next;
            tmp2 = tmp2->next;
        } else if (tmp1) {
            tmpSum += tmp1->val;
            rt = addNode(&head, tmpSum % 10);

            if (false == rt) {
                return NULL;
            }
            tmpSum = tmpSum / 10;

            tmp1 = tmp1->next;
        } else if (tmp2) {
            tmpSum += tmp2->val;
            rt = addNode(&head, tmpSum % 10);

            if (false == rt) {
                return NULL;
            }
            tmpSum = tmpSum / 10;
            tmp2 = tmp2->next;
        } else {
            break;
        }
    }
    //如果最高位還有進位,那麼需要創建一個新的節點來存儲該位信息
    if (tmpSum > 0) {
        addNode(&head, tmpSum);
    }

    return head;
}


發佈了410 篇原創文章 · 獲贊 19 · 訪問量 76萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章