I'm trying to implement the unique stack. If I try to extend the stack class and use the contains it will look the entire stack and the time complexity will become O(n). So I tried to extend the LinkedHashSet which will remove duplicates by itself and maintains the order. I'm able to implement all the methods except the pop.
Can anyone share thoughts here?
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Stack;
import java.util.stream.Stream;
public class UniqueStack<E> extends LinkedHashSet<E>{
private int size = 0;
@Override
public Stream<E> stream() {
return super.stream();
}
public boolean push(E e) {
if (!contains(e)) {
++size;
return super.add(e);
}
return false;
}
public E pop() {
// struck here
return;
}
}