113 lines
2.6 KiB
Java
113 lines
2.6 KiB
Java
import java.util.Iterator;
|
|
import java.util.LinkedList;
|
|
|
|
public class LongStack {
|
|
|
|
private final LinkedList<Long> lifo;
|
|
|
|
public static void main (String[] argum) {
|
|
long i = interpret("1 -2 45 -45");
|
|
|
|
}
|
|
|
|
LongStack() {
|
|
this.lifo = new LinkedList<>();
|
|
}
|
|
|
|
LongStack(LinkedList<Long> lifo) {
|
|
this.lifo = lifo;
|
|
}
|
|
|
|
@Override
|
|
public Object clone() throws CloneNotSupportedException {
|
|
return new LongStack((LinkedList<Long>) this.lifo.clone());
|
|
}
|
|
|
|
public boolean stEmpty() {
|
|
return this.lifo.isEmpty();
|
|
}
|
|
|
|
public void push (long a) {
|
|
this.lifo.push(a);
|
|
}
|
|
|
|
public long pop() {
|
|
return this.lifo.pop();
|
|
}
|
|
|
|
public void op (String s) {
|
|
if (s.equals("+")) {
|
|
this.lifo.push(this.lifo.pop() + this.lifo.pop());
|
|
} else if (s.equals("-")) {
|
|
long r1 = this.pop();
|
|
long r2 = this.pop();
|
|
this.lifo.push(r2 - r1);
|
|
} else if (s.equals("*")) {
|
|
this.lifo.push(this.lifo.pop() * this.lifo.pop());
|
|
} else if (s.equals("/")) {
|
|
long r1 = this.pop();
|
|
long r2 = this.pop();
|
|
this.lifo.push(r2 / r1);
|
|
} else if(s.equals(" ") | s.equals("\t")) {
|
|
return;
|
|
} else {
|
|
throw new RuntimeException("Invalid operation");
|
|
}
|
|
}
|
|
|
|
public long tos() {
|
|
return this.lifo.getFirst();
|
|
}
|
|
|
|
@Override
|
|
public boolean equals (Object o) {
|
|
return this.lifo.equals(((LongStack)o).lifo);
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
StringBuilder s = new StringBuilder();
|
|
Iterator<Long> i = this.lifo.descendingIterator();
|
|
while (i.hasNext()) {
|
|
s.append(i.next());
|
|
s.append(" ");
|
|
}
|
|
return s.toString();
|
|
}
|
|
|
|
public static long interpret (String pol) {
|
|
LongStack ls = new LongStack();
|
|
for(int i = 0; i < pol.length(); i++) {
|
|
char c = pol.charAt(i);
|
|
char nc = ' ';
|
|
if (i+1 < pol.length()) {
|
|
nc = pol.charAt(i + 1);
|
|
}
|
|
if ((c == '-' & nc >= '0' & nc <= '9')| (c >= '0' & c <= '9')) {
|
|
StringBuilder buf = new StringBuilder();
|
|
buf.append(c);
|
|
i++;
|
|
for (; i < pol.length(); i++) {
|
|
c = pol.charAt(i);
|
|
if (c >= '0' & c <= '9') {
|
|
buf.append(c);
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
ls.push(Long.parseLong(buf.toString()));
|
|
} else {
|
|
ls.op("" + c);
|
|
}
|
|
}
|
|
if (ls.lifo.size() == 1) {
|
|
return ls.pop();
|
|
} else {
|
|
throw new RuntimeException("Unbalanced polish notation");
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|