[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());
}
}
}
}
答案 0 :(得分:1)
您根本不需要删除任何内容(我的意思是不是通过调用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();
}
}