问题
[3, 5, 4, 2, 1] where I need the delete the nodes close to the tail which is it should be like [1, 2, 3, 5, 4] any suggestions?
public void delete() {
for(Node<T> current = getHead(); current != null; current = current.getNext()){
System.out.println(temp.getValue());
removeValue(temp.getValue());
}
}
}
}
回答1:
You don't need to remove anything at all (I mean not by calling removeValue
). Just store the values you encounter in a set and if the value is already in the set, re-link your list in consequence. If you don't have the right to use library code, implement your set with a binary search tree, it will be easy and quite efficient.
This is how I would do, assuming I have an implementation of 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();
}
}
来源:https://stackoverflow.com/questions/26823759/duplicate-the-singly-linked-list