【问题标题】:LinkedList indexOf method implementation [duplicate]LinkedList indexOf方法实现[重复]
【发布时间】:2020-09-21 16:59:10
【问题描述】:

我的一个程序中有以下方法:

/** 
 * Returns the index of the first occurrence of the specified item.
 * If the specified item in not part of the list
 * the method indexOf returns -1
 * 
 * @param item
 * @return index of the first occurrence of the item; -1 if the word was not found.
 */
public int indexOf(String item) {   

    int index = 0;

    //While we haven't reached the end of the list
    while(head != null) {
        //If the items are equal return true
        if(head.item == item) {
            return index;           
        }
        //Set the head to the next and increment the index  
        head = head.next;
        index++;
    }
    return -1;
}

虽然对我来说一切看起来都是正确的(除了需要将 head.item == item 更改为 head.item.equals(item)),但它并没有给我正确的索引。

虽然它确实给了我 -1 的元素,但每次它返回 0 作为列表中元素的索引时,我都无法弄清楚为什么索引是不递增。

任何意见将不胜感激!谢谢

【问题讨论】:

  • 这能回答你的问题吗? How do I compare strings in Java?
  • head 在哪里初始化?如果您第二次拨打indexOfhead 是否仍然是上次拨打电话后的null
  • 我得到了一个部分开始的 WordList 类型(字符串列表)。唯一的字段是头节点、尾节点和 int n(列表中的单词数)。该列表是在 main 方法中通过简单地将字符串附加到列表中来创建的(append 方法也已经为我编写了)。
  • 此外,append 方法肯定会追加到列表的末尾。我无法弄清楚这里出了什么问题。
  • 你能展示更多你的类定义吗?我想查看class 行本身和实例变量(如headtail)。不过,您不需要包含其他功能。

标签: java list linked-list increment


【解决方案1】:

当您遍历indexOfcontains 中的列表时,您似乎正在更改head 的值。 head 值应始终指向列表中的第一个条目,并且仅在 appendprepend 需要时进行更改。要进行迭代,您应该使用局部变量来循环遍历列表。您还应该使用.equals 来比较字符串值,而不是==

public int indexOf(String item) {   

    int index = 0;
    Node current = head;

    //While we haven't reached the end of the list
    while(current != null) {
        //If the items are equal return the index
        if(current.item.equals(item)) {
            return index;           
        }
        //Set current to the next and increment the index  
        current = current.next;
        index++;
    }
    return -1;
}

【讨论】:

  • 信不信由你我已经尝试过完全一样的,它没有任何区别。
  • 您是否将== 更改为.equalshead 变量的类型是什么?
  • 是的,我确实将其更改为 .equals。头部是 Node 类型,另一个已经包含的类,它只包含两个字段(String item 和 Node next)。
  • 我可以编辑我的原始帖子以包含所有代码,如果这样会更容易的话。
  • 我调整了我的解释。每次您拥有head = head.next 时,您都会丢失列表中原来的第一个Node
猜你喜欢
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 2016-12-12
  • 1970-01-01
  • 2013-04-06
  • 2019-12-15
相关资源
最近更新 更多