简体   繁体   中英

Java assignment

I have this Java 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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM