我目前正在实现一个带有虚拟头节点的循环双向链表。我的添加函数(在给定索引处,在开头或结尾处添加元素)似乎完美无缺,但我无法推断使函数indexOf(返回元素的索引)或删除(删除节点处于给定索引)方法。
调试时,indexOf似乎抓错了索引。给出一个列表:
[Alabama, Alaska, Arizona, Arkansas, Wyoming, California]
调用
list.remove(indexOf("Wyoming"));
返回
[Alabama, Alaska, Arizona, Arkansas, Wyoming, ]
这是indexOf函数:
public int indexOf(E e) {
Node<E> current = head;
for (int i = 0; i < size; i++) {
if (e.equals(current.element)) {
return i;
}
current = current.next;
}
return -1;
}
这是删除功能:
public E remove(int index) {
if (index < 0 || index >= size) {
throw new NoSuchElementException();
} else if (index == 0) {
return removeFirst();
} else if (index == size - 1) {
return removeLast();
} else {
Node<E> previous = head;
for (int i = 1; i < index; i++) {
previous = previous.next;
}
Node<E> current = previous.next;
previous.next = current.next;
size--;
return current.element;
}
}
如果head
应该始终是null
,那么你的indexOf()
方法似乎不正确
public int indexOf(E e) {
Node<E> current = head.next; // Add this to effectively begin with the first index of your list
for (int i = 0; i < size; i++) {
if (e.equals(current.element)) { // This will never be equals, because of the first time current being null
return i;
}
current = current.next;
}
return -1;
}