简体   繁体   English

通过Java链表中的索引检索元素

[英]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. 我正在编写一个链表(不使用Java),并试图创建一个get方法以通过其索引号返回该表的元素。 Originally, I wrote this using a for loop. 最初,我是使用for循环编写的。 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). 我的代码在测试中多次失败,该测试在索引0处检索元素(我似乎能够在其他索引处检索元素)。 curr is just for me to keep track of the current node. curr只是对我跟踪当前节点。

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. 我以为for循环可能会给我带来麻烦,因此我将其编写为while循环。

 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. 但是,我仍然很难在0索引处检索元素。 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? 您将curr初始化为sentinal.next ,这是否会导致您跳过第一个元素? You should also have an off-by-one error for every element, as if your list was 1-indexed instead of 0-indexed. 您还应该为每个元素设置一个错误的错误,就像列表是1索引而不是0索引一样。

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. 在while循环中,除非索引等于索引,否则您不会迭代i ,因此除非index为0,否则您永远找不到i == index的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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