Leetcode:2. Add Two Numbers(Week 6)

Description:

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

解題分析:

將兩個非空鏈表從頭到尾依次相加,得到一個新的鏈表,鏈表上的值爲和的個位數,若和超過10則將和/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 *prev = NULL, *result = NULL;
        int carry = 0;
        while (l1 || l2) {
            int v1 = l1? l1->val : 0;
            int v2 = l2? l2->val : 0;
            int sum = v1+v2 + carry;
            int value = sum%10;
            carry = sum/10;
            ListNode * cur = new ListNode(value);
            if (!result) result = cur;
            if (prev) prev->next = cur;
            prev = cur;

            l1 = l1 ? l1->next :NULL;
            l2 = l2 ? l2->next : NULL;
        }
        if (carry > 0) {
            ListNode * l = new ListNode(carry);
            prev->next = l;
        }
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章