[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();
}
}
关于java - 复制单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823759/