LeetCode Problem:Add Two Numbers

Problem 2: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


解題思路:

1.說白了就是在鏈表上模擬加法運算。對於那些比較怕鏈表操作出錯的人,可能會說,那我可不可以先把兩條鏈表分別轉換爲兩個數值,然後相加得到結果,然後再將結果生成一條鏈表,當然這種做法是不行的,因爲給定的鏈表可能會很長,也就是說該鏈表表示的數組可能會很大,比如幾百位,幾千位,這樣什麼int類型long類型都是存不了的。當然他們可以用動態數組解決。

2.一看該題就不是什麼算法優化題,純屬鏈表操作練習題。不過要注意一個細節,就是要處理好給定的兩個鏈表長度不一致的問題,或者給定的鏈表爲空(雖然不知道題目是否有沒有規定給定的鏈表至少有一個節點)。其實這道題很類似合併兩個有序數組爲一個有序數組那題(當然數組二字也可以換成鏈表)。

3.還有最好把相加兩個鏈表節點(包含進位)弄成一個函數,這樣代碼會整潔不少。

 

參考代碼:

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {

public:

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

        ListNode* p1 = l1;

        ListNode* p2 = l2;

        ListNode* head = NULL;

        ListNode* tail = NULL;

        int value;

        int carray = 0;

        while(p1 != NULL && p2 != NULL)

        {

            carray = addOneNode(p1->val,p2->val,carray,head,tail);

            p1 = p1->next;

            p2 = p2->next;

        }

        while(p1 != NULL)

        {

            carray = addOneNode(p1->val,0,carray,head,tail);

            p1 = p1->next;

        }

        while(p2 != NULL)

        {

            carray = addOneNode(0,p2->val,carray,head,tail);

            p2 = p2->next;

        }

        if(carray == 1)

        {

            ListNode* node = new ListNode(1);

            tail->next = node;

        }

        return head;

    }

 

private:

    int addOneNode(int val1,int val2,int carray,ListNode*& head,ListNode*& tail)

    {

        int value = val1 + val2 + carray;

        carray = 0;

        if(value >= 10)

        {

            carray = 1;

            value = value % 10;

        }

        ListNode* node = new ListNode(value);

        if(tail == NULL)

        {

            head = node;

            tail = node;

        }

        else

        {

            tail->next = node;

            tail = node;

        }

        return carray;

    }

};


轉載請註明原文地址:http://blog.csdn.net/u012619640/article/details/48197861

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