I have this Ja开发者_JAVA百科va assignment on linked list. The question asks for finding nth node from the last. I have tested it for different inputs and it works fine but the judge is not accepting my solution. Here is my function
The function takes the reference to the list head and the value of n which will always be non-negative.
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;
}
Sample input:
A -> B -> C -> D
n output
0 D
1 C
2 B
3 A
Can you please think of anything that is wrong in the function ?
I think you need to handle the case where input
n >= num of nodes
Your current function will give a NullPointerException for such an input.
EDIT:
You can count the number of nodes and compare. Alternatively you can make a check in your for
loop as:
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;
}
}
精彩评论