You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
這個題想完成還是比較簡單的,但是想完成高質量的結果還需要仔細斟酌,我介紹下我的低劣的AC代碼,題目中給的示例兩個數字是位數相同的,但是考慮到實際情況,肯定包含不等長的情況。爲了不另開闢空間,我首先對兩個鏈表進行了長度的比較,將長的數字和短的數字分別標記出來,然後之後的求和結果在長鏈表中進行更新覆蓋,求和時需要考慮當較短數字疊加完成後仍有進位的情況,並且需要考慮最終進位一直到長數字的最高位仍有進位的情況,這時需要再添加一個鏈表節點,將最終的進位添加上去。代碼如下:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x),next(NULL)
{}
};
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
if(l1 == NULL)
return l2;
else if(l2 == NULL)
return l1;
ListNode *l1Temp = l1;
ListNode *l2Temp = l2;
ListNode *longer,*shorter;
int length1=0,length2=0,carry=0,temp=0;
while(l1Temp != NULL)
{
length1++;
l1Temp = l1Temp -> next;
}
while(l2Temp != NULL)
{
l2Temp = l2Temp->next;
length2++;
}
if(length2 > length1)
{
longer = l2;
shorter = l1;
}
else
{
longer = l1;
shorter = l2;
}
l1Temp = longer;
l2Temp = shorter;
while(l1Temp != NULL && l2Temp != NULL)
{
if(carry != 0)
{
temp = l1Temp->val + l2Temp->val+carry;
carry = 0;
}
else
{
temp = l1Temp->val + l2Temp->val;
}
if(temp > 9)
{
carry = temp / 10;
l1Temp->val = temp%10;
}
else
{
l1Temp->val = temp;
}
l1Temp = l1Temp->next;
l2Temp = l2Temp->next;
}
if(carry != 0)
{
while(l1Temp != NULL && carry != 0)
{
temp = l1Temp->val + carry;
carry = temp / 10;
l1Temp->val = temp % 10;
l1Temp = l1Temp->next;
}
if(carry != 0)
{
ListNode *newNode = new ListNode(carry);
l1Temp = longer;
while(l1Temp->next != NULL)
l1Temp = l1Temp->next;
l1Temp->next = newNode;
}
}
return longer;
}
};