public class IterOriginator {
private final Node root;
private Node cursor = null;
private Boolean isDone = false;
private Stack<Node> stack;
private Memento<Node> memento;
public IterOriginator(Node root) {
this.root = root;
stack = new Stack<>();
cursor = root;
stack.push(cursor);
}
public Node next() {
memento = createMemento();
if (stack.isEmpty()) {
isDone = true;
return null;
}
Node top = stack.pop();
cursor = top.right;
if (cursor != null) {
stack.push(cursor);
}
cursor = top.left;
if (cursor != null) {
stack.push(cursor);
}
return top;
}
public void undo() {
setMemento(memento);
}
public Memento<Node> createMemento() {
Memento<Node> memento = new Memento<>();
Stack newStack=(Stack)stack.clone();
memento.status = newStack;
return memento;
}
public void setMemento(Memento<Node> memento) {
this.stack = memento.status;
}
}
public class Memento<T> {
public Stack<T> status;
}
public class Node {
public Node left;
public Node right;
public String name;
public Node(Node left, Node right, String name) {
this.left = left;
this.right = right;
this.name = name;
}
public Node(String name) {
this.name = name;
}
public IterOriginator createFrontIndexIterator() {
return new IterOriginator(this);
}
}
public class App {
public static void main(String[] args) {
Node one = new Node(
new Node(new Node(new Node("8"),null,"3"), new Node(new Node("6"), new Node("7"), "4"), "2"),
new Node(new Node("9"),null,"5"), "1");
IterOriginator iterOriginator=one.createFrontIndexIterator();
Memento first=iterOriginator.createMemento();
System.out.println(iterOriginator.next().name);
System.out.println(iterOriginator.next().name);
iterOriginator.setMemento(first);
System.out.println(iterOriginator.next().name);
System.out.println(iterOriginator.next().name);
}
}