题目:
分析题目
这种数位分开模拟手算过程的加法,一般都逆序存储各个位置方便进位。
本位 = (a+b+up)%10
进位 = (a+b+up)/10
普通递推法:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = nullptr, *tail = nullptr;
int up = 0;
while (l1 || l2) {
int n1 = l1 ? l1->val: 0;
int n2 = l2 ? l2->val: 0;
int sum = n1 + n2 + up;
int basic = sum % 10;
if (!head) {
head = tail = new ListNode(basic);
} else {
tail->next = new ListNode(basic);
//注意更新到最新的结点
tail = tail->next;
}
up = sum / 10;
//进行向后遍历
if (l1) {
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
//若最后l1和l2均被遍历完,但是仍有进位,则继续向前加一个数
if (up > 0) {
tail->next = new ListNode(up);
}
return head;
}
};
递归法yyds
struct ListNode* dfs(struct ListNode* l1,struct ListNode* l2,int up){
//当满足该条件递归结束,回访得到正确答案
if(!l1&&!l2&&!up)
return NULL;
//当l为空则这时候的要加的数变成0
int n1 = l1?l1->val:0;
int n2 = l2?l2->val:0;
int basic = (n1+n2+up)%10;//本位
int new_up = (n1+n2+up)/10;//进位
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = basic;
if(l1){
l1 = l1->next;
}
if(l2){
l2 = l2->next;
}
//把递归当while循环用。。。
head->next=dfs(l1,l2,new_up);
return head;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
return dfs(l1,l2,0);
}