LeetCode题解——两数相加
- 题目介绍
- 解题思路
- 同时遍历l1和l2,计算两个节点的数据和,注意一下进位
- 利用递归的方式遍历,只有当两个链表的next都为空的时候返回,但是返回时要看一下有没有上个节点的进位,没有就返回NULL,否则返回值为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* add(ListNode* l1, ListNode* l2,int value){
int total = value;
ListNode *res;
if(l1 == NULL && l2 == NULL){
if(value != 0){ //考虑进位
res = new ListNode(value);
res->next = NULL;
return res;
}
return NULL;
}
if(l1 != NULL) {
total += l1->val;
l1 = l1->next;
}
if(l2 != NULL) {
total += l2->val;
l2 = l2->next;
}
value = total/10;
res = new ListNode(total%10);
res->next = add(l1,l2,value);
return res;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
return add(l1,l2,0);
}
};