http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

C++ 解法，链表相加（需翻转）

```/**
* 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 *reverseList(ListNode *head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode *l = head, *r = l->next;
l->next = nullptr;
while (r) {
ListNode *t = r->next;
r->next = l;
l = r;
r = t;
}
return l;
}
ListNode *l1 = reverseList(head1);
ListNode *l2 = reverseList(head2);
ListNode *ans = new ListNode(0), *cur = ans;
int carry = 0;
while (l1 || l2 || carry) {
int x = l1 ? l1->val : 0;
int y = l2 ? l2->val : 0;
int sum = x + y + carry;
carry = sum / 10;
sum %= 10;
cur->next = new ListNode(sum);
cur = cur->next;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
ans = ans->next;
ans = reverseList(ans);
return ans;
}
};```

2022-12-15 15:50

01-03 12:41

2022-12-13 23:34

2022-12-07 15:10

2022-12-16 15:37

2022-12-26 14:32

2 1 评论