Leetcode:添加反向链接列表中表示的两个数字不起作用 [英] Leetcode: Adding two numbers represented in reverse linked list is not working
本文介绍了Leetcode:添加反向链接列表中表示的两个数字不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码不适用于以下输入:[2,4,3][5,6,4]输出:[7,8]预期的:[7,0,8]
The following code is not working for the below Input: [2,4,3] [5,6,4] Output: [7,8] Expected: [7,0,8]
为什么我没有得到0?谁能帮我.
Why I am not getting 0? Can anyone please help me.
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
return AddTwoNumbersHelper(l1, l2, 0);
}
private ListNode AddTwoNumbersHelper(ListNode l1, ListNode l2, int carry) {
if (l1 == null && l2 == null)
return null;
int temp = 0;
if (l1 != null)
temp += l1.val;
if (l2 != null)
temp += l2.val;
ListNode result = new ListNode(temp % 10);
carry = temp / 10;
l1 = l1.next;
l2 = l2.next;
int sum = 0;
while(l1 != null || l2 != null) {
sum = carry;
if (l1 != null)
sum += l1.val;
if (l2 != null)
sum += l2.val;
carry = sum == 0 ? 0 : sum / 10;
sum = sum % 10;
result.next = new ListNode(sum);
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
if (carry > 0)
result.next = new ListNode(carry);
return result;
}
}
推荐答案
代码存在一些缺陷:
- 除非您要递归的不是递归参数,否则方法中不需要进位参数.
- 列表提升步骤(l = l.next)可以与将节点的值添加到temp(sum)变量的步骤结合在一起.
- 您不需要编写额外的代码来处理悬空的手提箱,循环就足够了,只需在循环中包含条件即可.
- 该错误是因为您在每次迭代中不断更新头部的下一个指针,而不是在链接列表中构建(添加一个节点).您需要一个额外的指针/变量来做到这一点.
- "sum"是比"temp"更好的变量名.
这是经过稍微修改的解决方案,可以解决上述问题:
Here's a slightly modified solution which fixes the above problems:
private ListNode AddTwoNumbersHelper(ListNode l1, ListNode l2) {
ListNode result = null;
ListNode tail = null;
int carry = 0;
while ((l1 != null) || (l2 != null) || (carry != 0)) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
carry = sum/10;
sum %= 10;
if (result == null) { // first time
result = new ListNode(sum);
tail = result;
} else {
tail.next = new ListNode(sum);
tail = tail.next;
}
}
return result;
}
这篇关于Leetcode:添加反向链接列表中表示的两个数字不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文