[LeetCode]--Add Two Numbers

題目

    You are given two non-empty linked lists representing two non-negative integers. 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.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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

    中文題意:給出兩個非空鏈表分別代表兩個非負整數。數字按照逆序存儲並且每個節點只包含單個數字。求兩數的和並返回鏈表形式。

分析

         因爲數字按照逆序存儲,顯然題中所給的示例中兩數分別爲:342,465。而342+465=807。因此最終返回數807的逆向存儲列表7->0->8。
       剛開始在寫這道題的時候,想當然地認爲兩個鏈表的長度相同。而這恰恰是我們思維的一個誤區。題中並沒有提及兩鏈表的長度,因此有可能是不同的,這就需要事先判斷指針是否指向null,即鏈表是否將爲空,若爲空則建立一個新的存儲數字“0”的節點。
       解決了這個問題,這道題就很容易Pass了。我們先建立一個新列表result(將結果存儲在其中),然後遍歷兩個給出列表中的對應節點並做加法運算。值得注意的是,兩數相加若大於10,我們將利用取模(%)運算得到本位結果,利用除法(/)運算得到進位結果保存在carry中並在下一位的加法運算過程中加上carry。如果兩鏈表的所有非空節點都已遍歷完,且carry>0時,則需要新創建一個節點以保存運算結果的最高位。

解答

/**
 * 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* m=l1; 
        ListNode* n=l2;
        ListNode* result=new ListNode(0);
        ListNode* cur=result;
        int carry=0;
        int sum=0;
        while(m!=NULL || n!=NULL){
            if(m==NULL) {
                m=new ListNode(0);
            }
            if(n==NULL) {
                n=new ListNode(0);
            }
            sum=(m->val)+(n->val)+carry;
            carry=sum/10;
            //cout<<carry<<" "<<sum<<endl;
            cur->next=new ListNode(sum%10);
            cur=cur->next;
            if(m!=NULL) m=m->next;
            if(n!=NULL) n=n->next;
            sum=0;
        }
        if(carry>0){
            cur->next=new ListNode(carry);
        }
        return result->next;
    }
};

         不難得出,該算法的複雜度爲O(max{l1.size(), l2.size()})

  

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