gpt4 book ai didi

Java赋值

转载 作者:行者123 更新时间:2023-11-29 08:15:17 25 4
gpt4 key购买 nike

我在链表上有这个 Java 作业。该问题要求从最后一个节点中找到第 n 个节点。我已经针对不同的输入对其进行了测试,它工作正常,但法官不接受我的解决方案。这是我的功能

该函数采用对列表头的引用和始终为非负数的 n 的值。

Node findNtoLast ( Node start, int n)
{
Node p,q;

p = start;

for(int i=0;i<n;i++)
{
p = p.next;
}

q = start;

while(p.next != null)
{
p = p.next;
q = q.next;
}

return q;
}

示例输入:

A -> B -> C -> D

n     output
0 D
1 C
2 B
3 A

你能想到函数中有什么错误吗?

最佳答案

我认为你需要处理输入的情况

n >= num of nodes

您当前的函数将为此类输入提供 NullPointerException。

编辑:

你可以统计节点的数量并进行比较。或者,您可以在 for 循环中进行检查,如下所示:

for(int i=0;i<n;i++) {

// have I reached the last node ?
if (p.next != null) {
p = p.next;
} else {
// n happens to be >= num of nodes..return null
return null;
}
}

关于Java赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5295489/

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