2 .两数相加 https://leetcode.cn/problems/add-two-numbers/
敏捷开发,先实现最基本的功能
int sumval = cur1->val + cur2->val+carry;
if(sumval >= 10){
curRes->val = sumval-10;
carry = 1;
}else{
curRes->val = sumval;
carry = 0;
}
原链表需要遍历,返回链表需要新建next
cur1 = cur1->next;
cur2 = cur2->next;
if(cur1 && cur2){
curRes->next = new ListNode(0);
curRes = curRes->next;
}
判断语句是控制循环只发生在对齐的部分
处理没有对齐的部分
curRes->next = cur1? cur1: cur2;
1 2 3 4
1 1 1
会变成
2 3 4 4
1 1 1 1
1 2 3
会变成
2 3 4 1
一般情况这样就好了,但别忘了有可能前面余下来进位了
9
9 9 1 1 1
不处理的话结果是:8 9 1 1 1
没有考虑18的进位
所以要考虑这个
while(curRes->next){
curRes = curRes->next;
int sumval = curRes->val+carry;
if(sumval >= 10){
curRes->val = sumval-10;
carry = 1;
}else{
curRes->val = sumval;
carry = 0;
}
}
还有一个特殊情况
9 9 9
9
不考虑最后进位是
8 0 0
但最后还有进位
所以carry等于1再加个next
if(carry==1){
curRes->next = new ListNode(1);
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* cur1 = l1;
ListNode* cur2 = l2;
ListNode* res = new ListNode(0);
ListNode* curRes = res;
int carry = 0;
while(cur1 && cur2){
int sumval = cur1->val + cur2->val+carry;
if(sumval >= 10){
curRes->val = sumval-10;
carry = 1;
}else{
curRes->val = sumval;
carry = 0;
}
cur1 = cur1->next;
cur2 = cur2->next;
if(cur1 && cur2){
curRes->next = new ListNode(0);
curRes = curRes->next;
}
}
curRes->next = cur1? cur1: cur2;
while(curRes->next){
curRes = curRes->next;
int sumval = curRes->val+carry;
if(sumval >= 10){
curRes->val = sumval-10;
carry = 1;
}else{
curRes->val = sumval;
carry = 0;
}
}
if(carry==1){
curRes->next = new ListNode(1);
}
return res;
}
};