英文:
Writing singly Linked List class from scratch - remove, indexOf methods not working
问题
我正在从头开始编写单向链表类,但是在某些地方,我的remove和likely indexOf方法不起作用。
public E remove(int index){
if(index < 0 || index > size-1)
throw new IndexOutOfBoundsException("IndexOutOfBounds");
if(index == 0) {
E temp1 = head.data;
Node temp2 = head.next;
head.next = null;
head = temp2;
return temp1;
}
Node<E> hopper = getNode(index-1);
Node<E> toRemove = hopper.next;
E temp = toRemove.data;
hopper.next = hopper.next.next;
toRemove.data = null;
toRemove.next = null;
return temp;
}
对于remove方法,我怀疑在某些情况下存在边缘案例或一些逻辑错误。在我的JUnit测试器中,它似乎根本没有删除任何内容。至于indexOf方法:
public int indexOf(Object o){
if(o == null) {
Node<E> hopper = head;
for(int i = 0; i < size-1; i++) {
if(hopper.data == o)
return i;
hopper = hopper.next;
}}
else {
Node<E> hopper = head;
for(int i = 0; i < size-1; i++) {
if(hopper.data.equals(o))
return i;
hopper = hopper.next;
}}
return -1;
}
在我的JUnit测试器中,contains方法不起作用,而该方法实际上只是调用indexOf来执行搜索。
如果需要,我可以提供任何其他代码。如果有人能够帮助解释我出错的地方,我将非常感谢。谢谢!
英文:
I am writing the singly linked list class from scratch but somewhere my remove at an index and likely indexOf methods are not working.
public E remove(int index){
if(index < 0 || index > size-1)
throw new IndexOutOfBoundsException("IndexOutOfBounds");
if(index == 0) {
E temp1 = head.data;
Node temp2 = head.next;
head.next = null;
head = temp2;
return temp1;
}
Node<E> hopper = getNode(index-1);
Node<E> toRemove = hopper.next;
E temp = toRemove.data;
hopper.next = hopper.next.next;
toRemove.data = null;
toRemove.next = null;
return temp;
}
For remove, I suspect there is a fringe case or some logical error somewhere. In my JUnit tester, it appears to not remove anything at all. And as for indexOf:
public int indexOf(Object o){
if(o == null) {
Node<E> hopper = head;
for(int i = 0; i < size-1; i++) {
if(hopper.data == o)
return i;
hopper = hopper.next;
}}
else {
Node<E> hopper = head;
for(int i = 0; i < size-1; i++) {
if(hopper.data.equals(o))
return i;
hopper = hopper.next;
}}
return -1;
}
In my JUnit tester, contains does not work and that method literally just calls indexOf to do the search.
I can provide any additional code if needed. If someone could help explain where I am going wrong, I would greatly appreciate it. Thanks!
专注分享java语言的经验与见解,让所有开发者获益!
评论