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

标签 java data-structures linked-list singly-linked-list

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

例如:

移除前

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

移除后

全部删除(5)

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

查了很多java DS,没找到java中完美的。

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

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

感谢您的帮助:)


编辑 - 1

找到指定要删除的元素(在示例中为 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();
    }
}

最佳答案

嗯,java.util.LinkedList 实现了 List 接口(interface),它有一个 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();

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

关于java - Java中的数据结构,具有删除节点后的所有节点的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48062131/

相关文章:

c - 在C中使用链表

java - 无法将数据库结果存储到映射中

java - 单击对话框时替换另一个 fragment 上方的 fragment (viewpager)

java - 无法远程启动 WebLogic 进行调试

java - 使用 Gson 将 Json 解析为具有通用字段的项目列表

java - 在 Java 中使用正则表达式提取值

java - 重新排列LastN - Java

javascript - 为前端组件实现树形数据结构

c - bsearch() 在 C 中的字符串数组上

algorithm - 为什么单链表有多个头是一件好事?