All tests pass

This commit is contained in:
Arti Zirk 2016-10-02 19:36:20 +03:00
parent 5625a31752
commit e7158c799e
1 changed files with 72 additions and 12 deletions

View File

@ -1,51 +1,111 @@
import java.util.Iterator;
import java.util.LinkedList;
public class LongStack {
private final LinkedList<Long> lifo;
public static void main (String[] argum) {
// TODO!!! Your tests here!
long i = interpret("1 -2 45 -45");
}
LongStack() {
// TODO!!! Your constructor here!
this.lifo = new LinkedList<>();
}
LongStack(LinkedList<Long> lifo) {
this.lifo = lifo;
}
@Override
public Object clone() throws CloneNotSupportedException {
return this; // TODO!!! Your code here!
return new LongStack((LinkedList<Long>) this.lifo.clone());
}
public boolean stEmpty() {
return false; // TODO!!! Your code here!
return this.lifo.isEmpty();
}
public void push (long a) {
// TODO!!! Your code here!
this.lifo.push(a);
}
public long pop() {
return 0; // TODO!!! Your code here!
} // pop
return this.lifo.pop();
}
public void op (String s) {
// TODO!!!
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 0; // TODO!!! Your code here!
return this.lifo.getFirst();
}
@Override
public boolean equals (Object o) {
return true; // TODO!!! Your code here!
return this.lifo.equals(((LongStack)o).lifo);
}
@Override
public String toString() {
return null; // TODO!!! Your code here!
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) {
return 0; // TODO!!! Your code here!
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");
}
}
}