题目链接
注意点
- 考虑位数不一样的情况以及首位有进位的情况
解法
解法一:模拟加法,用变量carry保存进位。遍历链表,先算长度相同的部分,然后算长度多出来的那部分,随时要更新carry的值。最后判断carry的值因为会有首位进位的情况。时间复杂度为O(n)
/**
* 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) {
int carry = 0;
ListNode* anw = new ListNode(carry);
ListNode* pointer = anw;
while(l1 != NULL && l2 != NULL)
{
pointer->next = new ListNode((carry+l1->val+l2->val)%10);
pointer = pointer->next;
carry = (carry+l1->val+l2->val)/10;
l1 = l1->next;
l2 = l2->next;
}
while(l1 != NULL)
{
pointer->next = new ListNode((carry+l1->val)%10);
pointer = pointer->next;
carry = (carry+l1->val)/10;
l1 = l1->next;
}
while(l2 != NULL)
{
pointer->next = new ListNode((carry+l2->val)%10);
pointer = pointer->next;
carry = (carry+l2->val)/10;
l2 = l2->next;
}
if(carry != 0)
{
pointer->next = new ListNode(carry);
pointer = pointer->next;
}
return anw->next;
}
};
}
小结
- 以前做过类似的题目,所以一下就有思路了,就是链表的使用想了好一会...