题目描述(难度中)
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
链接
https://leetcode-cn.com/problems/add-two-numbers/
思路
特殊情况考虑:
1、都是0的情况,需要返回0
0
0
ans:0
2、当l1和l2都为空,但是进位还存在值时需要特殊考虑一下
5
5
ans:01
其他的即为常规链表操作
代码
/**
* 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) {
if(l1 == NULL && l2 == NULL){
return NULL;
}
else if(l1 == NULL && l2 != NULL){
return l2;
}
else if(l1 != NULL && l2 == NULL){
return l1;
}
else{
ListNode* ansHead = NULL;
ListNode* ansNext = NULL;
ListNode* temp1 = l1;
ListNode* temp2 = l2;
int index = 0;
int jinwei = 0;
while(temp1 && temp2){
index = (temp1->val + temp2->val + jinwei) % 10;
jinwei = (temp1->val + temp2->val + jinwei) / 10;
ListNode* listTemp = new ListNode(index);
if(ansHead == NULL){
ansHead = listTemp;
ansNext = ansHead;
}
else{
ansNext->next = listTemp;
ansNext = ansNext->next;
}
temp1 = temp1->next;
temp2 = temp2->next;
}
while(temp1){
index = (temp1->val + jinwei) % 10;
jinwei = (temp1->val + jinwei) / 10;
ListNode* listTemp = new ListNode(index);
ansNext->next = listTemp;
ansNext = ansNext->next;
temp1 = temp1->next;
}
while(temp2){
index = (temp2->val + jinwei) % 10;
jinwei = (temp2->val + jinwei) / 10;
ListNode* listTemp = new ListNode(index);
ansNext->next = listTemp;
ansNext = ansNext->next;
temp2 = temp2->next;
}
if(jinwei){
ListNode* listTemp = new ListNode(1);
ansNext->next = listTemp;
}
return ansHead;
}
}
};