首页 > 解决方案 > 从头开始编写单个链接列表类 - 删除,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 来进行搜索。

如果需要,我可以提供任何额外的代码。如果有人可以帮助解释我哪里出错了,我将不胜感激。谢谢!

标签: javadata-structureslinked-listindexof

解决方案


推荐阅读