题解 | #链表相加(二)#
链表相加(二)
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* addInList(ListNode* head1, ListNode* head2) {
// write code here
head1=reverseList(head1);
head2=reverseList(head2);
vector<int> sum;
int t=0;
while(head1||head2)
{
if(head1) t+=head1->val,head1=head1->next;
if(head2) t+=head2->val,head2=head2->next;
sum.emplace_back(t%10);
t=t/10;
// cout<<t<<endl;
}
if(t) sum.emplace_back(1);
int n=sum.size();
ListNode* dummy=new ListNode(-1);
ListNode* current=dummy;
for(int i=n-1;i>=0;i--)
{
ListNode* node=new ListNode(sum[i]);
current->next=node;
current=current->next;
}
return dummy->next;
}
ListNode* reverseList(ListNode* head)
{
ListNode* current=head;
ListNode* prev=nullptr;
while(current)
{
ListNode* tmp=current->next;
current->next=prev;
prev=current;
current=tmp;
}
return prev;
}
};
用了一个链表反转和大数加和。