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 楼答案
嗯,
java.util.LinkedList
实现了List
接口,它有一个subList()
方法。使用该方法,您可以获得原始列表尾部的子列表,并通过清除它来截断原始列表:从Javadoc:
这要求您知道要从中删除所有元素的节点的索引