【问题标题】:How do you implement your own lastIndexOf(E e) for LinkedLists in java?你如何在java中为链表实现你自己的lastIndexOf(E e)?
【发布时间】:2021-12-15 19:56:06
【问题描述】:
public int lastIndexOf(E e) {
// Left as an exercise
// TODO : Implement this method
Node<E> current = tail;

不知道如何完成这个 for 循环:

for (int i = size - 1; i >= 0; i--) {
    if(e.equals(current))
        return i;
    
} 

return -1;

}

这个程序要求我为我自己的 LinkedList 接口创建一个 lastIndexOf 方法。 lastIndexOf(E e) 应该返回找到元素e 的索引。这与indexOf(E e) 不同,因为算法要求我从列表的末尾而不是开头查找

【问题讨论】:

    标签: java interface implementation interface-implementation


    【解决方案1】:

    for 循环的反向迭代看起来不错。但是,你在比较错误的东西。

    您可以使用this.get(index) 获取当前元素。

    public int lastIndexOf(E e) {    
        for (int i = size - 1; i >= 0; i--) {
            E element = get(i);
            if (e == null && element == null) return i;
            if (e != null && e.equals(element)) return i;
        } 
        
        return -1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 2015-01-27
      • 2011-01-11
      相关资源
      最近更新 更多