1. 程式人生 > >題解——Leetcode 2. Add Two Numbers 難度:Medium

題解——Leetcode 2. Add Two Numbers 難度:Medium

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

本題要求將以連結串列儲存的兩個整數相加,求和的結果依然儲存在一個連結串列中,最後返回結果連結串列的頭指標。

題目的難點在於

1. 兩個整數逆序儲存,低位向高位有進位時不再是向前而是向後進位。

2. 兩個整數不一定有相同的位數,所以遍歷連結串列時要判斷是否遍歷結束,如果結束,就將其相應位置為0。

3. 兩個整數的最高位相加可能產生進位。

綜上考慮,我們建立一個新的連結串列,其頭節點為head,指向其的頭指標為p,我們用carry表示對應位相加後的進位,sum表示相加後結果。

sum等於兩個整數對應位相加再加上低位進位,sum向高位的進位carry = sum / 10,此時結果連結串列新增一個節點,其val = sum % 10即p->next = new ListNode(sum % 10)。這樣便完成了一次加法和進位操作,結果連結串列和兩個儲存整數的連結串列的指標向後移動一位,重複之前的加法和進位操作,直到兩個整數遍歷結束且不存在進位。

/**
 * 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 head(0), *p = &head;
        int carry = 0;
        
        while(l1 || l2 || carry){
            int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
            carry = sum / 10;
            p->next = new ListNode(sum % 10);
            
            p = p->next;
            l1 = l1 ? l1->next : l1;
            l2 = l2 ? l2->next : l2;
        }
        return head.next;
    }
};