问题:
难度:medium
说明:
给出两个链表,然后每个链表节点都只存放一个数字,要求将两个链表当做两个数字,进行相加,然后返回结果。
题目连接:https://leetcode.com/problems/add-two-numbers-ii/
输入范围:
- The number of nodes in each linked list is in the range
[1, 100]
. 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
输入案例:
Example 1:
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0]
Output: [0]
我的代码:
其实和两个字符串,数组相加一样,只不过弄成了链表。
Java:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int len1 = 0, len2 = 0, len;
ListNode temp = l1, longer, shorter;
for(;temp != null; len1 ++, temp = temp.next);
temp = l2;
for(;temp != null; len2 ++, temp = temp.next);
if(len1 >= len2) {
longer = l1; shorter = l2; len = len1;
while(len1 > len2) {
ListNode append = new ListNode(0);
append.next = shorter;
shorter = append;
len2 ++;
}
} else {
longer = l2; shorter = l1; len = len2;
while(len2 > len1) {
ListNode append = new ListNode(0);
append.next = shorter;
shorter = append;
len1 ++;
}
}
int carry = recurtion(longer, shorter, 1, len);
if(carry != 0) {
ListNode append = new ListNode(1);
append.next = longer;
longer = append;
}
return longer;
}
public int recurtion(ListNode longer, ListNode shorter, int index, int len) {
int carry = 0;
if(index != len) carry = recurtion(longer.next, shorter.next, index + 1, len);
int val = longer.val + shorter.val + carry;
longer.val = val % 10;
return val / 10;
}
}
C++:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int len1 = 0, len2 = 0, len;
ListNode* temp = l1, *longer, *shorter;
for(;temp != nullptr; len1 ++, temp = temp->next);
temp = l2;
for(;temp != nullptr; len2 ++, temp = temp->next);
if(len1 >= len2) {
longer = l1; shorter = l2; len = len1;
while(len1 > len2) {
ListNode* addition = new ListNode(0);
addition->next = shorter;
shorter = addition;
len2 ++;
}
} else {
longer = l2; shorter = l1; len = len2;
while(len2 > len1) {
ListNode* addition = new ListNode(0);
addition->next = shorter;
shorter = addition;
len1 ++;
}
}
int carry = recurtion(longer, shorter, 1, len);
if(carry) {
ListNode * addition = new ListNode(1);
addition->next = longer;
longer = addition;
}
return longer;
}
int recurtion(ListNode* longer, ListNode* shorter, int index, int len) {
int carry = 0;
if(index != len) carry = recurtion(longer->next, shorter->next, index + 1, len);
int val = longer->val + shorter->val + carry;
longer->val = val % 10;
return val / 10;
}
};