1. 程式人生 > >Leetcode Algorithms : 2. Add Two Numbers

Leetcode Algorithms : 2. Add Two Numbers

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

設計

思路和平時做加法計算是一樣的。從低位往高位,兩個數的對應位與上一個低位的進位相加,得到該位的和以及進位。最高位相加後,如果還有進位,就再往高位寫下該進位。

/**
 * 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* sum = SumOfTwoNumbers(l1, l2); return sum; } private: int carry; bool isSoluted; ListNode* SumOfTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* sum = new ListNode
(0); ListNode* top = sum; carry = 0; isSoluted = false; while (!isSoluted) { sum->val = sumOfCorrespondingBitsAndCarry(l1, l2); carry = sum->val / 10; sum->val %= 10; if (l1 != NULL) l1 = l1->next; if (l2 != NULL) l2 = l2->next; isSoluted = isCalculationFinished(l1, l2); buildNextNodeOfSum(sum); if (sum->next != NULL) sum = sum->next; } addFinalCarryToSum(sum); return top; } int sumOfCorrespondingBitsAndCarry(ListNode* l1, ListNode* l2) { int left = (l1 != NULL) ? l1->val : 0; int right = (l2 != NULL) ? l2->val : 0; return left + right + carry; } bool isCalculationFinished(ListNode* l1, ListNode* l2) { return (l1 == NULL && l2 == NULL); } void buildNextNodeOfSum(ListNode* sum) { if (!isSoluted) sum->next = new ListNode(0); else sum->next = NULL; } void addFinalCarryToSum(ListNode* sum) { if (carry != 0) sum->next = new ListNode(carry); carry = 0; } };

分析

假設l1長度為m,l2長度為n。時間複雜度就是O(max(m, n)),空間複雜度也是O(max(m, n))。 程式碼的設計還有不少不足之處。首先是SumOfTwoNumbers函式有20行,顯得有些長了;其次是buildNextNodeOfSum和addFinalCarryToSum函式使用的是輸出引數。引數多數會被當做是函式的輸入,使用輸出引數可能會造成理解上的困擾和檢查函式宣告的代價。最後,在和的連結串列構造上我的做法麻煩了一些,不如leetcode的答案精巧。