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的答案精巧。