[3,5,4,2,1]我需要删除靠近尾部的节点,这应该像[1,2,3,5,4]有什么建议吗?
public void delete() {
for(Node<T> current = getHead(); current != null; current = current.getNext()){
System.out.println(temp.getValue());
removeValue(temp.getValue());
}
}
}
}
您根本不需要删除任何内容(我的意思是不需要调用removeValue
)。只需将您遇到的值存储在一个集合中,如果该值已经在集合中,则相应地重新链接您的列表。如果你没有使用库代码的权利,用二进制搜索树来实现你的集合,这将是简单而高效的。
假设我有Set
:的实现,我会这样做
public void makeUnique() {
Set<T> set = new MySet<>();
Node<T> current = getHead();
Node<T> previous = null;
while (current != null) {
// if current.getValue() is already in the set, we skip this node
// (the add method of a set returns true iff the element was not
// already in the set and if not, adds it to the set)
if (set.add(current.getValue()) {
// previous represents the last node that was actually inserted in the set.
// All duplicate values encountered since then have been ignored so
// previous.setNext(current) re-links the list, removing those duplicates
if (previous != null) {
previous.setNext(current);
current.setPrevious(previous);
}
previous = current;
}
current = current.getNext();
}
}