Java赋值

Java赋值,java,data-structures,linked-list,Java,Data Structures,Linked List,我在链表上有这个Java作业。该问题要求从最后一个节点中查找第n个节点。我测试了不同的输入,效果很好,但法官不接受我的解决方案。这是我的功能 该函数引用列表头和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(

我在链表上有这个Java作业。该问题要求从最后一个节点中查找第n个节点。我测试了不同的输入,效果很好,但法官不接受我的解决方案。这是我的功能

该函数引用列表头和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;
}

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

我想你需要处理输入错误的情况

n >= num of nodes
当前函数将为此类输入提供NullPointerException

编辑:

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

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;
   }
}
for(int i=0;i=num of nodes..return null
返回null;
}
}

我认为您需要处理输入

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;
   }
}
for(int i=0;i=num of nodes..return null
返回null;
}
}

使用比
n
@Jon短的列表尝试函数-如果列表的大小已知,则任务更简单。使用比
n
@Jon短的列表尝试函数-如果列表的大小已知,则任务更简单。你是对的人。我应该计算节点的数量并进行比较吗?你是对的人。应该吗我计算节点数并比较?