-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUndoStack.java
71 lines (62 loc) · 1.84 KB
/
UndoStack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package vertexCover.advanced;
import core.Graph;
/**
* {@link UndoStack} is a class which represents a single-linked-list.
* Is is used to avoid copying a {@link Graph}, because creating a new {@link Graph} and copying all the data from the old one is very time-consuming.
*/
public class UndoStack {
/**
* Item to hold an operation to undo changes made to a {@link Graph}.
*/
public abstract static class UndoItem { // abstract class because interface can't have fields (otherwise it would be better to use a FunctionalInterface)
/**
* Previous {@link UndoItem} in a {@link UndoStack}.
*/
private UndoItem prev = null;
/**
* Runs code to undo changes made to a {@link Graph}.
*/
public abstract void undo();
}
private UndoItem tail;
private int size;
/**
* Constructs a new empty {@link UndoStack}.
*/
public UndoStack() {
tail = null;
size = 0;
}
/**
* Returns the number of {@link UndoItem}s in this {@link UndoStack}.
*
* @return the number of {@link UndoItem}s in this {@link UndoStack}
*/
public int size() {
return size;
}
/**
* Returns the last (newest) {@link UndoItem} on this {@link UndoStack}.
*
* @return the last (newest) {@link UndoItem} on this {@link UndoStack}
*/
public UndoItem pop() {
if (size != 0) {
UndoItem temp = tail;
tail = tail.prev;
size--;
return temp;
}
return null;
}
/**
* Appends the given {@link UndoItem} at the end of this {@link UndoStack}.
*
* @param ui is the {@link UndoItem} which will be added to this {@link UndoStack}
*/
public void push(UndoItem ui) {
ui.prev = tail;
tail = ui;
size++;
}
}