【问题标题】:Circular Doubly-Linked List indexOf and remove functions incorrect循环双向链表 indexOf 和删除函数不正确
【发布时间】:2019-07-23 18:55:18
【问题描述】:

我目前正在实现一个带有虚拟头节点的循环双向链表。我的添加函数(在给定索引处、开始处或结尾处添加元素)似乎完美无缺,但我无法推断出一个功能 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;

    }
}

【问题讨论】:

  • 如果将 for(...) 循环从 i &lt; index 更改为 i &lt; index-1 会发生什么
  • 这进一步打破了它;如果我将 i ,它会失败之前的测试
  • 当您说您有一个虚拟头节点时,您的意思是head 永远不会为空吗? head引用的元素是列表中的第一个元素,还是head.next是列表中的第一个元素?
  • Head 应该始终为 null,head.next 应该是列表的第一个元素。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多