LeetCode 2. 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

對兩個鏈表做加法,每個結點的值只能是個位數,向后進位;
對于兩個鏈表不一樣長的情況,可以讓短的鏈表后面的值都為0,也可以直接把長的鏈表多余的部分鏈接到ans鏈表的尾。但在本題中,因為要處理進位,如果兩個鏈表分別是[1];[9,9,9,9],結果是[0,0,0,0,1],不能直接把多余的連接到表尾,因此采用第一種處理方式。

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* ans = new ListNode(0);
        ListNode* P = ans;  // P指向結果鏈表的最后一位
        int count = 0;
        while(l1 || l2){
            if(l1){
                count += l1->val;
                l1 = l1->next;
            }
            if(l2){
                count += l2->val;
                l2 = l2->next;
            }
            P->next = new ListNode(count % 10);
            P = P->next;
            count /= 10;
        }
        if(count) {  // 如果l1,l2都為空,但剩余一個進位,需要新增加結點
            P->next = new ListNode(1);
        }
        return ans->next;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容