Leetcode:添加反向链接列表中表示的两个数字不起作用

编程入门 行业动态 更新时间:2024-10-11 07:32:56
本文介绍了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:添加反向链接列表中表示的两个数字不起作用

    本文发布于:2023-11-30 07:54:51,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1649255.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:不起作用   两个   链接   数字   列表中

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!