Skip to content

Instantly share code, notes, and snippets.

@ondrej-kvasnovsky
Created June 18, 2015 01:32
Show Gist options
  • Save ondrej-kvasnovsky/3688ccc9d10f2a023c76 to your computer and use it in GitHub Desktop.
Save ondrej-kvasnovsky/3688ccc9d10f2a023c76 to your computer and use it in GitHub Desktop.
Back and forward implementation
import java.util.ArrayDeque;
import java.util.Deque;
public class History<ENTITY> {
private Deque<ENTITY> backStack = new ArrayDeque<>();
private Deque<ENTITY> forwardStack;
private ENTITY current;
private int max;
public History(int max) {
this.max = max;
}
public void record(ENTITY entity) {
if (backStack.size() >= max) {
backStack.pollFirst();
}
if (!entity.equals(current)) {
current = entity;
backStack.add(entity);
forwardStack = new ArrayDeque<>();
}
}
public ENTITY back() {
ENTITY back = backStack.pollLast();
if (back != null) {
forwardStack.add(current);
}
if (current.equals(back)) {
back = backStack.pollLast();
}
if (back != null) {
current = back;
}
return back;
}
public ENTITY forward() {
ENTITY forward = forwardStack.pollLast();
if (forward != null) {
backStack.add(current);
}
if (current.equals(forward)) {
forward = forwardStack.pollLast();
}
if (forward != null) {
current = forward;
}
return forward;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment