简体   繁体   English

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

[英]Circular Doubly-Linked List indexOf and remove functions incorrect

I am currently implementing a circular doubly-linked list with a dummy head node. 我目前正在使用虚拟头节点实现循环双向链接列表。 My add functions (adding an element at a given index, at the start, or at the end) seem to work flawlessly, but I cannot extrapolate to make a functioning indexOf (which returns the index of an element) or remove (remove node at given index) method. 我的add函数(在给定索引处,在开始处或在末尾处添加元素)似乎可以正常工作,但是我无法推断出要使功能正常的indexOf(返回元素的索引)或删除(删除节点处的节点)。给定索引)方法。

When debugging, indexOf seems to grab the wrong index. 调试时,indexOf似乎获取了错误的索引。 When given a list of: 当给出以下列表:

[Alabama, Alaska, Arizona, Arkansas, Wyoming, California]

Calling 调用

list.remove(indexOf("Wyoming"));

Returns 返回

[Alabama, Alaska, Arizona, Arkansas, Wyoming, ]

Here is the indexOf function: 这是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;
}

And here is the remove function: 这是删除功能:

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;

    }
}

If head should always be null , then your indexOf() method doesn't seem correct 如果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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM