-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOperatorStack.java
96 lines (85 loc) · 2.37 KB
/
OperatorStack.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public class OperatorStack {
public OperatorStackElement top = null;
public OperatorStackElement getLast(int depth, int lvl) {
cleanUp(depth);
if (top == null) {
return null;
}
// first op with max 1 level diff and also on the same depth
OperatorStackElement looker = top;
int levelDiff = looker.elem.opLevel - lvl;
if (levelDiff <= 1) {
// System.out.println("last: " + looker.elem.value);
return looker;
}
while (looker != null) {
// the or is for in brackets
// System.out.println(" --- " + looker.elem.value + " | " +
// looker.elem.opLevel);
if (looker.elem.bracketDepth == depth) {
// System.out.println(" --- right depth");
levelDiff = looker.elem.opLevel - lvl;
if (levelDiff <= 1) {
// System.out.println("found last: " + looker.elem.value);
return looker;
}
} else { // this is also for in brackets, might change later FIXME maybe ?
return top;
}
if (looker.next != null) {
looker = looker.next;
} else {
break;
}
}
// System.out.println("notfound last: " + top.elem.value);
return top; // XXX MIGHT BLOW UP !?
}
public void printStack() {
if (top != null) {
System.out.println("------ top");
top.printStack();
System.out.println("--- bottom");
}
}
public EquationNode getAbove(int depth) { // above in the tree, below in the stack
// important for cases like 5*(2^3+8)
// the + in brackets needs to add above the ^
// But also "link" back to the *
OperatorStackElement looker = top;
while (looker != null) {
if (looker.elem.bracketDepth < depth) {
return looker.elem;
}
looker = looker.next;
}
return null;
}
public void add(EquationNode elem, int depth) {
elem.bracketDepth = depth;
OperatorStackElement newTop = new OperatorStackElement(elem);
if (top != null) {
cleanUp(depth);
// unsorted variant
newTop.next = top;
top = newTop;
} else {
top = newTop;
}
}
private void cleanUp(int depth) {
while (top != null) {
if (top.elem.bracketDepth > depth) {
pop();
} else {
break;
}
}
}
public void pop() {
if (top != null) {
// System.out.println("-- rm: " + top.elem.value);
top = top.next;
}
}
}