题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
class Solution {
public:
ListNode* addInList(ListNode* head1, ListNode* head2) {
ListNode* l1 = reverseList(head1);//翻转链表1
ListNode* l2 = reverseList(head2);//翻转链表2
ListNode* head = nullptr;
ListNode* tail = nullptr;
int carry = 0; //进位
while (l1 || l2) {
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int sum = n1 + n2 + carry;
if (!head) {
head = new ListNode(sum % 10);
tail = head;
} else {
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
if (l1) l1 = l1->next;//循环
if (l2) l2 = l2->next;
carry = sum / 10;
}
tail->next = carry ? new ListNode(carry) : nullptr;//尾部节点
ListNode* pHead = reverseList(head);
return pHead;
}
ListNode* reverseList(ListNode* head) {//翻转链表
ListNode* cur = head;
ListNode* pre = nullptr;
while (cur) {
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
Leetcode刷题整合 文章被收录于专栏
都是作者刷到的一些感觉是好题整理到一起的,辛苦整理不易,麻烦给个赞,有疑问请留言