【问题标题】:Return location of first occurrence and return -1 if not found within the circular linked list返回第一次出现的位置,如果在循环链表中找不到则返回 -1
【发布时间】:2021-09-24 21:34:32
【问题描述】:

如果在循环链表中找不到,我试图将 -1 分配给索引。这是我目前的代码:

public int indexOf(int value){
    Node temp = tail.next;
    int count = 0;
    int index = 0;
    
    while(temp != null) {
        if(temp.value == value) {
            index = count;
            return index;
        }
        count++;
        temp = temp.next;
    }

    return index -1;
    
}

当我测试代码时,结果如下:

列表应该是 [8 12 14]: [ 8 12 14] *** 测试指数 *** 8的索引应该是0:0 14的索引应该是2:2

代码停止,它应该打印索引 9,它不在列表中,应该是 -1。我不知道如何解决这个问题。我的代码只是运行并且不会产生更多结果(无论如何也不是以一种节省时间的方式)。

我必须这样做吗:

while(temp == null){ 
index = -1;
break; 
  }

感谢您的帮助!

【问题讨论】:

  • 如果它是一个循环列表,你的 while 循环将永远不会结束
  • 您需要某种方式知道何时检查了每个元素,以便您可以停止并返回 -1。我建议保留对您检查的第一个节点的引用,看看当前节点是否与第一个节点相同。即使保持循环执行的条件仍然成立,您也可以使用break 立即退出循环。你的问题最后的while循环没有意义。由于您的列表是循环的,因此 temp 永远不会为空,并且该循环可能只是一个 if 语句。 if(temp == null) index = -1;
  • 这就是我的想法,但我不确定如何在代码中描述它。我对链表不太熟悉。我遇到了一个关于 null 的错误,这就是我创建最后一个 while 循环的原因。但它与这个特定的方法无关。谢谢你的解释!

标签: java data-structures circular-list


【解决方案1】:

正如 cmets 中的 Kaus 所指出的,您的 while 循环永远不会在当前状态下结束。假设 tail 实际上指向列表中的最后一个元素,可以使用以下代码:

public int indexOf(int value) {
    Node head = tail.next; //tail should be connected to a head
    Node current = head;
    int index = 0;
    do {
        if (current.value == value) {
            return index;
        }
        current = current.next;
        ++index;
    } while (current != head);
    return -1;
}

遍历所有元素(从头部开始),如果再次遇到头部则结束(假设没有找到搜索值)。

【讨论】:

  • 这正是我想要的!非常感谢!
猜你喜欢
  • 2021-02-05
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 2012-05-09
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多