445. Add Two Numbers II

  • 46.0%

https://leetcode.com/problems/add-two-numbers-ii/description/

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:

What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

1
2
3
4
Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

方法一:

类似于 2. Add Two Numbers

此题的区别在于要反转链表,然后相加,再反转回去。

我的代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(!l1) return l2;
else if(!l2) return l1;
ListNode* p1 = reverseListNode(l1);
ListNode* p2 = reverseListNode(l2);
ListNode* dummy = new ListNode(-1);
ListNode* cur = dummy;
int carry = 0;
while(p1 || p2 || carry){
carry += p1 ? p1->val : 0;
carry += p2 ? p2->val : 0;
cur->next = new ListNode(carry%10);
carry /= 10;
cur = cur->next;
if(p1) p1 = p1->next;
if(p2) p2 = p2->next;
}
return reverseListNode(dummy->next);
}

ListNode* reverseListNode(ListNode* head){ // 返回的是ListNode* 不是ListNode
if(!head) return NULL;
ListNode* pre = NULL;
while(head){
ListNode* nex = head->next;
head->next = pre;
pre = head;
head = nex;
}
return pre;
}
};
谢谢你,可爱的朋友。