题解
直接依次遍历,每一位两两相加进位
- 用光标记录当前位置
- 注意存在最高位有进位的情况
- l1、l2移动时,需要满足非空条件
/**
* 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) {}
* };
*/
#include<cmath>
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* root =new ListNode(-1);
ListNode* cursor=root;
bool carry=false;
int sum;
//存在最高位进位情况
while(l1!=0 || l2!=0 ){
sum=0;
//计算当前位置的和
if(l1!=NULL){
sum+=l1->val;
l1=l1->next;}
if(l2!=NULL){
sum+=l2->val;
l2=l2->next;}
if(carry)
sum++;
//申请下一个节点,并将光标移动到当前节点
ListNode* nextNode =new ListNode(sum%10);
cursor->next=nextNode;
cursor=nextNode;
carry=sum>=10?true:false;
}
//最高位有进位情况,直接申请新的val为1的节点
if(carry)
{
cursor->next=new ListNode(1);
}
return root->next;
}
};