鏈表求和

描述:你有兩個用鏈表代表的整數,其中每個節點包含一個數字。數字存儲按照在原來整數中相反的順序,使得第一個數字位於鏈表的開頭。寫出一個函數將兩個整數相加,用鏈表形式返回和。
樣例
給出兩個鏈表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
思路:剛開始想着用其原來的鏈表來進行在基礎上的求和 後面發現當兩個鏈表的長度不一致時 會出現不知道以哪個鏈表爲基準 後面 想着用一個新的鏈表來存儲兩個鏈表的和。在while(1){ }循環裏面判斷兩個鏈表是否到了NULL,如果其中一個鏈表沒有到NULL或者和有進位,則繼續開闢一個新的節點來存取和的低位。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the sum list of l1 and l2 
     */
    ListNode *addLists(ListNode *l1, ListNode *l2) {
        // write your code here
        int tmp=0;
        ListNode *head=new ListNode(0);
        ListNode *result=head;
        while(1)
        {
            if(l1 != NULL)
            {
                tmp += l1->val;
                l1=l1->next;
            }
            if(l2 != NULL)
            {
                tmp += l2->val;
                l2=l2->next;
            }
            result->val = tmp % 10;//將低位存儲到鏈表中
            tmp = tmp / 10;//將進位轉移到低位
            if(l1 != NULL || l2 != NULL || tmp)
                result=result->next=new ListNode(0);
            else
                break;

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