0

我必须编写一个名为 LastIndexOf 的方法,该方法接受一个整数值作为参数,并返回该值最后一次出现的列表中的索引,如果未找到该值,则返回 -1。这是我拥有的代码,但它不返回任何内容。对我来说,它看起来总是会返回 -1 但我在输出中看不到它,因为它不打印该方法返回的内容。

这些是列出商店的值。

列表 -> [2, 5, 7, 24, 5, 9, 13, 2]

    public class LastIndexOf {

    public static void main(String[] args) {

    System.out.println("index of 5 = " + list.lastIndexOf(5)); // should to return index of 5= 4
    System.out.println("index of 100 = " + list.lastIndexOf(100)); // should return index of 100 = -1

    }

    public static int lastIndexOf (int element) {
    int index = 0;
    ListNode current = list;
    while (current != null) {
       if (current.data == element) {
           return index;
       }
       index ++;
       current = current.next;
    }
    return -1;
    }
}

这是我得到的输出:

index of 5 = 
index of 100 = 
4

3 回答 3

0

此代码不应有 2 个返回语句。此外,您正在使节点等于整个列表;当它应该等于列表的头部时。

这个代码是给你纠正的吗?我问是因为它似乎不是分段开发的;相反,它看起来是从上到下写的。

于 2014-04-28T00:28:45.753 回答
0

此代码段返回正确的值。

public class Test
{
    public static java.util.List<Integer> list = Arrays.asList(2, 5, 7, 24, 5, 9, 13, 2);

    public static void main(String[] args)
    {

        System.out.println("index of 5 = " + list.lastIndexOf(5));
        System.out.println("index of 100 = " + list.lastIndexOf(100));

        System.out.println(lastIndexOf(5));
        System.out.println(lastIndexOf(100));
    }


    public static int lastIndexOf (int element) {
    int index = 0;
    int found = -1;
    List<Integer> current = list;
    while (index < current.size()) {
       if (current.get(index) == element) {
           found = index;
       }
       index ++;
    }
    return found;
    }
}

我不知道 ListNode 是干什么用的,因为它实际上是不需要的。

我想鼓励你看看 openjdk 中的 ArrayList<> 实现是怎样的:ArrayList.java#ArrayList.lastIndexOf in OpenJDK

于 2014-04-28T00:36:57.453 回答
0

我猜使用这个:

    public int lastIndexOf (int value) {
        int index = -1;
        int size = size();
        int count = 0;

        ListNode current = front;

        for (int i = 0; i < size; i++) {
            int indexValue = current.data;
            if (value == current.data) {index = count;}
            count++;
            current = current.next;
         }
         return index;
     }
于 2015-08-05T05:43:33.977 回答