题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
链表翻转相加,结果再翻转
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
//链表反转 相加 再反转
ListNode* newList1 = reverse(head1);
ListNode* newList2 = reverse(head2);
ListNode* dh = new ListNode(0),*cur = dh;
int c = 0,num=0;
//有进位、任意链表还有长度
while(newList1||newList2||c){
//每一位相加
int tmp=(newList1?newList1->val:0) + (newList2?newList2->val:0)+c;
//处理进位
c = tmp/10;
num = tmp%10;
//将结果载入新链表
ListNode* n = new ListNode(num);
cur->next = n;
cur = cur->next;
//处理链表迭代
newList1 = newList1==nullptr?nullptr:newList1->next;
newList2 = newList2==nullptr?nullptr:newList2->next;
}
//翻转最后结果
return reverse(dh->next);
}
//迭代翻转
ListNode* reverse(ListNode* head){
ListNode* pre = nullptr,*cur = head,*next = cur->next;
while(cur!=nullptr){
cur->next = pre;
pre = cur;
cur = next;
next = next->next;
}
return pre;
}
};