题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
C++ 版本
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* reverse(ListNode* pHead) {
ListNode* cur = pHead;
ListNode* pre = NULL;
while(cur){
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
ListNode* l1 = nullptr, *l2 = nullptr;
if(!head1) return head2;
else l1 = reverse(head1);
if(!head2) return head1;
else l2 = reverse(head2);
ListNode* dummy = new ListNode(0);
ListNode* ans = dummy;
int jinwei = 0;
int value = 0;
while (l1 || l2 || jinwei) {
value = jinwei;
if (l1) {
value += l1->val;
l1 = l1->next;
}
if (l2) {
value += l2->val;
l2 = l2->next;
}
jinwei = value / 10;
value = value % 10;
ans->next = new ListNode(value);
ans = ans->next;
}
return reverse(dummy->next);
}
};
