题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* reverseList(ListNode* head){//链表翻转
auto L=new ListNode(0);
ListNode* p=head,*q=nullptr;
while(p){
q=p->next;
p->next=L->next;
L->next=p;
p=q;
}
return L->next;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
ListNode *L1=reverseList(head1);
ListNode *L2=reverseList(head2);
ListNode *L3=L1;
ListNode *pre=NULL;//断点的前驱
int res=0;
int jinwei=0;
int yushu=0;
while(L1&&L2){
res=L1->val+L2->val+jinwei;
jinwei=res/10;
yushu=res%10;
L1->val=yushu;
pre=L1;
L1=L1->next;
L2=L2->next;
}
while(L1){//L2完成
res=L1->val+jinwei;
jinwei=res/10;
yushu=res%10;
L1->val=yushu;
pre=L1;
L1=L1->next;
}
if(L2){//L1完成
pre->next=L2;
while(L2){
res=L2->val+jinwei;
jinwei=res/10;
yushu=res%10;
L2->val=yushu;
pre=L2;
L2=L2->next;
}
}
if(jinwei){//最后进位
ListNode* s=new ListNode(1);
pre->next=s;
}
return reverseList(L3);
}
};
查看14道真题和解析
