题解 | 链表相加(二)
链表相加(二)
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* reverse(ListNode* head){
ListNode* first=nullptr;
ListNode* second=head;
ListNode* third;
while(second!=nullptr){
third=second->next;
second->next=first;
first=second;
second=third;
}
return first;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
int tem=0;
head1=reverse(head1);
head2=reverse(head2);
ListNode* nhead=new ListNode(-1);
ListNode* origin_head=nhead;
while(head1!=nullptr||head2!=nullptr){
int val=tem;
if(head1!=nullptr){
val+=head1->val;
head1=head1->next;
}
if(head2!=nullptr){
val+=head2->val;
head2=head2->next;
}
tem=val/10;
val=val%10;
nhead->next=new ListNode(val);
nhead=nhead->next;
}
if(tem>0){
nhead->next=new ListNode(tem);
nhead=nhead->next;
}
return reverse(origin_head->next);
}
};
查看13道真题和解析