题解 | 链表相加(二) 注意思路 还可以用栈 以及注释的细节
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
//一开始想遍历形成字符串再转int 再相加再生成结点 但可能会遇到溢出等问题
//所以还是使用反转 按位相加
if(head1==nullptr)return head2;
if(head2==nullptr)return head1;
ListNode* p1=reverse(head1);
ListNode* p2=reverse(head2);
ListNode* dommy=new ListNode(0);
ListNode* cur=dommy;
int sum=0;
while(p1!=nullptr||p2!=nullptr){
/*这段没考虑一个结束了,另一个没有结束怎么办
int sum=num+p1->val+p2->val;
ListNode *node=new ListNode(sum%10);
cur->next=node;
cur=cur->next;
num=sum/10;
p1=p1->next;
p2=p2->next;
*/
if(p1!=nullptr){
sum+=p1->val;
p1=p1->next;
}
if(p2!=nullptr){
sum+=p2->val;
p2=p2->next;
}
cur->next=new ListNode(sum%10);
cur=cur->next;
sum/=10;
}
if(sum!=0){
cur->next=new ListNode(sum);
}
return reverse(dommy->next);
}
ListNode* reverse(ListNode* head){
//ListNode* dommy=new ListNode(0); 没用到
if(head==nullptr)return nullptr;
//重要!反转后 head作为尾结点 不能有next 要设为null 否则会成环
ListNode* pre=head,*cur=head->next;
head->next=nullptr;
while(cur!=nullptr){
ListNode* tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
};