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) return l2;
        if (l2 == NULL) return l1;
        ListNode* result = new ListNode(0);
        ListNode* tail = new ListNode(0);
        int flag = 0;
        result->next = tail;
        tail->val = (l1->val+l2->val)%10;
        if ((l1->val+l2->val) >= 10) {
            flag = 1;
        } else {
            flag = 0;
        }
        ListNode* temp1 = l1->next;
        ListNode* temp2 = l2->next;
        while (temp1 != NULL && temp2 != NULL) {
            ListNode* n = new ListNode((temp1->val+temp2->val+flag)%10);
            tail->next = n;
            tail = n;
            if ((temp1->val+temp2->val+flag) >= 10) {
                flag = 1;
            } else {
                flag = 0;
                }
            temp1 = temp1->next;
            temp2 = temp2->next;
        }
        if (!temp1) {
            while (temp2) {
                ListNode* n = new ListNode((temp2->val+flag)%10);
                if ((temp2->val+flag) >= 10) {
                    flag = 1;
                } else {
                    flag = 0;
                }
                tail->next = n;
                tail = n;
                temp2 = temp2->next;
            }
        }
        else if (!temp2) {
            while (temp1) {
                ListNode* n = new ListNode((temp1->val+flag)%10);
                if ((temp1->val+flag) >= 10) {
                    flag = 1;
                } else {
                    flag = 0;
                }
                tail->next = n;
                tail = n;
                temp1 = temp1->next;
            }
        }
        if (flag) {
            ListNode* f = new ListNode(flag);
            tail->next = f;
            tail = f;
        }
        result = result->next;
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章