Java 链接列表节点跳过循环并移动到下一个参数
我正在尝试练习leetcode示例。 输入- [2,4,3] [5,6,4] 预期产出=[7,0,8];(2+5、4+6、3+4+1(节点2结转1)); 我得到的是[7,8] q、 next和p.next-跳过第2个节点的添加,仅对第1个和第3个节点进行添加。 我无法理解为什么跳过第二个节点Java 链接列表节点跳过循环并移动到下一个参数,java,linked-list,Java,Linked List,我正在尝试练习leetcode示例。 输入- [2,4,3] [5,6,4] 预期产出=[7,0,8];(2+5、4+6、3+4+1(节点2结转1)); 我得到的是[7,8] q、 next和p.next-跳过第2个节点的添加,仅对第1个和第3个节点进行添加。 我无法理解为什么跳过第二个节点 public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class Solut
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode extra = new ListNode(0);
ListNode p = l1 , q = l2, curr = extra;
int carry = 0;
while(p != null || q != null)
{
int x = (p != null) ? p.val :0 ;
int y = (q != null) ? q.val :0 ;
int sum = carry + x + y ;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
p=p.next;
q=q.next;
if(p != null)p = p.next;
if(q != null)q = q.next;
}
if(carry > 0)
{
curr.next = new ListNode(carry);
}
return curr;
}
}
根据答案编辑-我在leetcode中检查了下面的代码。它仍然说产出是[0,8]
而不是[7,0,8]
以下是问题的联系:
你有多余的钱
p = p.next
q = q.next
这将导致跳过奇数索引(基于0)。这应该删除,因为只有
if(p != null)p = p.next;
if(q != null)q = q.next;
只要将
ListNode
的指针的增量都超过应该的值就足够了。在本部分:
while(p != null || q != null)
{
int x = (p != null) ? p.val :0 ;
int y = (q != null) ? q.val :0 ;
int sum = carry + x + y ;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
p=p.next; /* You increment the pointers right after this */
q=q.next;
if(p != null)p = p.next; // You don't even need this if statement either, thats what the while loop checks.
if(q != null)q = q.next;
}
此外,您应该在(p!=null&&q!=null)时放入,而不是|
,然后在跳出循环后放入任何剩余值
如果需要,您可以查看我的解决方案:
正如在其他答案中已经提到的那样,p
和q
在每次迭代中都会提前两次(有NullPointerException
BTW的风险)
而且,curr
从来都不是高级的,因此每次迭代时都会覆盖extra.next
方法返回的curr
指向方法末尾列表的最后一个元素。请尝试返回extra.next
(如果extra
为空且至少需要一个元素,则返回extra
)
正确的。这两个问题都很好。我尝试了这个,并编辑了我的问题。请检查它是否仍然不起作用,因为我说你必须在while循环中输入一个&&而不是| |,然后再输入任何额外的数字。因为你必须在while循环中输入一个&&而不是| |,然后再添加任何非空数字。看看我的解,看看我的意思;如果(p!=null)p=p.next;你在这里跳过了一个节点,和q一样。我尝试了这个并编辑了我的问题。请检查它是否仍然不工作
while(p != null || q != null)
{
int x = (p != null) ? p.val :0 ;
int y = (q != null) ? q.val :0 ;
int sum = carry + x + y ;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
p=p.next; /* You increment the pointers right after this */
q=q.next;
if(p != null)p = p.next; // You don't even need this if statement either, thats what the while loop checks.
if(q != null)q = q.next;
}
ListNode extra = new ListNode(0);
ListNode p = l1 , q = l2, curr = extra;
int carry = 0;
while(p != null || q != null)
{
int x = (p != null) ? p.val :0 ;
int y = (q != null) ? q.val :0 ;
int sum = carry + x + y ;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if(p != null)p = p.next;
if(q != null)q = q.next;
}
if(carry > 0)
{
curr.next = new ListNode(carry);
}
return extra.next == null ? extra : extra.next;