有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的数据结构,带有删除节点后所有节点的操作

我正在寻找Java中的(预定义的)数据结构,它将删除节点后的所有元素。 下面给出了一个代表性示例

例如:

移除前

head
 ┕>1 -> 2 -> 3 -> 4 -> 5 -> 6 ->7

移除后

移除(5)

head
┕>1 -> 2 -> 3 -> 4

我检查了很多java DS,但在java中没有找到一个完美的

(1.首选java.util中的数据结构

二,。头部插入和迭代是我正在使用的其他操作)

谢谢你的帮助:)


编辑-1

在找到指定要删除的元素(在示例its 5中)后,我们只需要删除下一个节点之间的链接

我检查了给出的答案的实现,但在这两种情况下,它都会分别删除每个节点。 只是好奇想知道其他的方法。:)

public void clear() {
    removeRange(0, size());
}

protected void removeRange(int fromIndex, int toIndex) {
    ListIterator<E> it = listIterator(fromIndex);
    for (int i=0, n=toIndex-fromIndex; i<n; i++) {
        it.next();
        it.remove();
    }
}

共 (1) 个答案

  1. # 1 楼答案

    嗯,java.util.LinkedList实现了List接口,它有一个subList()方法。使用该方法,您可以获得原始列表尾部的子列表,并通过清除它来截断原始列表:

    list.subList(firstIndexToRemove,list.size()).clear();
    

    从Javadoc:

    List java.util.List.subList(int fromIndex, int toIndex)

    Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

    This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

    list.subList(from, to).clear();

    这要求您知道要从中删除所有元素的节点的索引