无法解决Doubly Linked列表的indexOf函数

时间:2021-04-17 07:20:55

I have a function that I can't seem to figure out.

我有一个我似乎无法弄清楚的功能。

Instructions:

说明:

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element index is 0-based (i.e., the first 'real' node (after dummy header) is index 0). @param x the element to search for

返回此列表中第一次出现的指定元素的索引,如果此列表不包含元素索引,则返回-1(即,第一个“真实”节点(在虚拟标题之后)是索引0)。 @param x要搜索的元素

So, what's happening here is the function is passed in an Object, in my case a number. IndexOf is supposed to go through the list of numbers and see if any match. If it finds a match, it will return the INDEX of the object. My issue is that it just returns whatever result is initialized to. How can I make it so it returns the index?

所以,这里发生的是函数在Object中传递,在我的例子中是一个数字。 IndexOf应该通过数字列表,看看是否有任何匹配。如果找到匹配项,它将返回对象的INDEX。我的问题是它只返回初始化的结果。我该怎么做才能返回索引?

public int indexOf(Object x)
{
    Node current = head; 
    int result = 0;
    for(int i = 0; i < elementCount; i++){
        if(x.equals(current.data)){
          result = i;
          return result;
        }
    }
    return result;
}

1 个解决方案

#1


1  

Your 'current' always points to the head, so even though you're running the for loop for all the elements in the list, you are at every stage comparing 'x' with whatever is in the head.

你的'当前'总是指向头部,所以即使你为列表中的所有元素运行for循环,你也会在每个阶段将'x'与头部中的任何元素进行比较。

So, in your for loop, after your test, you should increment 'current'.

因此,在你的for循环中,在测试之后,你应该增加'current'。

for(int i = 0; i < elementCount; i++){
    if(x.equals(current.data)){
         result = i;
         return result;
    }
    current = current.next; // increment current pointer so that it 
                            // points to the next node in the list
}

Also, ideally, you should not initialize result to 0, but to -1. So if x in not found at all, your method will return -1 (instead of 0, which is deceiving).

另外,理想情况下,不应将结果初始化为0,而应初始化为-1。因此,如果根本找不到x,则您的方法将返回-1(而不是0,这是欺骗)。

#1


1  

Your 'current' always points to the head, so even though you're running the for loop for all the elements in the list, you are at every stage comparing 'x' with whatever is in the head.

你的'当前'总是指向头部,所以即使你为列表中的所有元素运行for循环,你也会在每个阶段将'x'与头部中的任何元素进行比较。

So, in your for loop, after your test, you should increment 'current'.

因此,在你的for循环中,在测试之后,你应该增加'current'。

for(int i = 0; i < elementCount; i++){
    if(x.equals(current.data)){
         result = i;
         return result;
    }
    current = current.next; // increment current pointer so that it 
                            // points to the next node in the list
}

Also, ideally, you should not initialize result to 0, but to -1. So if x in not found at all, your method will return -1 (instead of 0, which is deceiving).

另外,理想情况下,不应将结果初始化为0,而应初始化为-1。因此,如果根本找不到x,则您的方法将返回-1(而不是0,这是欺骗)。