java - 从头开始编写单个链接列表类 - 删除,indexOf 方法不起作用
问题描述
我正在从头开始编写单链表类,但是我在某个索引处删除并且可能 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;
}
对于删除,我怀疑某处存在边缘案例或某些逻辑错误。在我的 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 来进行搜索。
如果需要,我可以提供任何额外的代码。如果有人可以帮助解释我哪里出错了,我将不胜感激。谢谢!
解决方案
推荐阅读
- azure-ad-b2c - 哪些 AppInsights 查询会为 Azure B2C 身份验证返回可操作的数据?
- javascript - 如何从数组中移动所有值但删除最后一个值
- swift - 带有计时器不停止的标签
- elasticsearch - Debian Elasticsearch 插件已安装但未显示
- vue.js - 如何在没有 CLI / Webpack / Node 的情况下制作 Vue 3 应用程序
- php - 你可以在 PHP 中的函数内设置一个常量类属性吗?
- python - 为什么while循环函数不能在这里工作并给我错误
- swift - 如何在 LazyVGrid 中使用 GeometryReader
- node.js - express(NodeJS)有多少个副本?
- c++ - C 和 C++ 中的 Array-in-struct 初始化