我试图解决https://leetcode.com/problems/add-two-numbers,这个问题很容易,但由于借用问题我无法完成它。我尝试了几个 3 小时,但我怀疑ListNode的next字段类型Option<Box<ListNode>>不正确。
当我切换到 c# 时,我很快就解决了这个问题。以下是c#版本的解决方案。我无法将其翻译为生锈。
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
ListNode re = null;
ListNode next = null;
int carry = 0;
while(l1 != null || l2 != null) {
var val = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;
carry = val / 10;
val %= 10;
if (re != null){
next.next = new ListNode(val);
next = next.next;
} else {
re = new ListNode(val);
next = re;
}
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry > 0) {
next.next = new ListNode(carry);
}
return re;
}
}