题解 | #链表相加(二)#
链表相加(二)
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){
if(!head) return head;
ListNode *pre=NULL;
ListNode *cur=head;
while(cur){
ListNode *tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
if(!head1) return head2;
if(!head2) return head1;
head1=reverse(head1);
head2=reverse(head2);
ListNode* head = new ListNode(0);
ListNode* cur = head;
int uper = 0;
while(head1 || head2){
int val=uper;
if(head1) {
val+=head1->val;
head1=head1->next;
}
if(head2) {
val+=head2->val;
head2=head2->next;
}
uper=val/10;
cur->next=new ListNode(val%10);
cur=cur->next;
}
if(uper!=0){
cur->next=new ListNode(uper);
}
return reverse(head->next);
}
};
查看11道真题和解析
搜狐畅游公司福利 1309人发布