循环双链表indexOf和remove函数不正确

时间:2019-03-01 17:40:14

标签: java intellij-idea data-structures doubly-linked-list circular-list

我目前正在使用虚拟头节点实现循环双向链接列表。我的add函数(在给定索引处,在开始处或在末尾处添加元素)似乎可以正常工作,但是我无法推断出要使功能正常的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;

    }
}

1 个答案:

答案 0 :(得分:0)

如果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;
}