gpt4 book ai didi

java - 无法找到两个链表的两种迭代类型之间的区别

转载 作者:行者123 更新时间:2023-11-30 01:47:16 24 4
gpt4 key购买 nike

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

Following is the code I wrote:

ListNode dummy = new ListNode(0);
ListNode cur = dummy;
int add = 0;
while (r1 != null && r2 != null){
int sum = r1.val + r2.val + add;
add = sum / 10;
cur.next = new ListNode(sum % 10);
cur = cur.next;
r1 = r1.next;
r2 = r2.next;
}
if (r1 != null){
int sum = r1.val + add;
add = sum / 10;
cur.next = new ListNode(sum % 10);
cur = cur.next;
r1 = r1.next;
}
if (r2 != null){
int sum = r2.val + add;
add = sum / 10;
cur.next = new ListNode(sum % 10);
cur = cur.next;
r2 = r2.next;
}
if (add == 1){
cur.next = new ListNode(1);
}

最佳答案

您的算法可以描述如下,是正确的:

  1. 在其中一个列表未用完时添加两个列表的元素,
  2. 添加第一个列表中剩余的“尾部”元素,
  3. 添加第二个列表中剩余的“尾部”元素,
  4. 如果不为零则添加“进位”/

第 2 步和第 3 步中,只有一个为非空。

您的实现问题在于您实现 2 和 3 的方式:由于您使用的是 if,因此最多会添加一个元素,而不是处理整个“尾部”。

if 替换为 while 将解决此问题。

关于java - 无法找到两个链表的两种迭代类型之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57496226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com