简体   繁体   中英

Retrieving an element by index in Java linked list

I am writing a linked list (not using Java's) and trying to create a get method to return an element of the list by its index number. Originally, I wrote this using a for loop. My code is repeatedly failing a test in which it retrieves the element at index 0 (I seem to be able to retrieve elements at other indices). curr is just for me to keep track of the current node.

public double get(int index) {
    Node curr = this.sentinel.next;

    for (int i = 0; i < this.size(); i++) {
        if (i == index) {
            return curr.data;
        }
        curr = curr.next;
        if (index > numElts) {
            return Double.NaN;
        }
        if (index < 0) {
            return Double.NaN;
        }
    }
    return Double.NaN;
}

I thought the for loop might be what was giving me trouble, so I wrote it as a while loop.

 while (curr != null) {
  if (i == index) {
   i++;
   return curr.data;
 }
 curr = curr.next;
 }

However, I'm still having trouble retrieving the element at the 0 index. I appreciate any input on how these methods of traversal might be problematic. I'm kind of lost. Also apologies if my formatting is off, still getting used to formatting on this site.

You're initializing curr as sentinal.next , wouldn't this cause you to skip over the first element? You should also have an off-by-one error for every element, as if your list was 1-indexed instead of 0-indexed.

In the while loop, you're not iterating i unless it's equal to the index, so you'll never find the case that i == index unless index is 0.

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