Skip to content

Instantly share code, notes, and snippets.

@mxrguspxrt
Created October 5, 2012 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxrguspxrt/3838481 to your computer and use it in GitHub Desktop.
Save mxrguspxrt/3838481 to your computer and use it in GitHub Desktop.
java2-home3.java
public class Answer {
public static void main (String[] argum) {
Answer answer = new Answer();
}
class Linked {
public int value;
public Linked parent;
Linked(int value, Linked parent) {
this.value = value;
this.parent = parent;
}
public boolean equals (Linked o) {
if(o==null) return false;
if(this.value!=o.value) return false;
if(this.parent==o.parent) return true;
if(this.parent!=null && o.parent!=null && this.parent.equals(o.parent)) return true;
return false;
}
public Linked clone () {
if(this.parent!=null) {
return new Linked(this.value, this.parent.clone());
} else {
return new Linked(this.value, null);
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
if(this.parent!=null) sb.append(this.parent.toString() + " ");
sb.append(this.value);
return sb.toString();
}
}
public Linked last;
Answer() {
}
Answer(Linked last) {
this.last = last;
}
@Override
public Object clone() throws CloneNotSupportedException {
return new Answer(last.clone());
}
public boolean stEmpty() {
if(null==last) {
return true;
} else {
return false;
}
}
public void push (int a) {
last = new Linked(a, last);
}
public int pop() {
Linked popped = last;
last = popped.parent;
return popped.value;
}
public void op (String s) {
int b = this.pop();
int a = this.pop();
if(s.equals("+")){ this.push(a+b); }
else if(s.equals("-")){ this.push(a-b); }
else if(s.equals("*")){ this.push(a*b); }
else if(s.equals("/")){ this.push(a/b); }
else{ throw new RuntimeException("unknown character: '"+s+"'"); }
}
public int tos() {
return last.value;
}
@Override
public boolean equals (Object o) {
if(o==null) return false;
Answer other = (Answer)o;
if(this.last==other.last) return true;
if(this.last==null || other.last==null) return false;
return this.last.equals(other.last);
}
@Override
public String toString() {
if(this.last==null) return "";
return this.last.toString();
}
public static int interpret (String pol) {
pol = pol.replaceAll("\t", " ");
pol = pol.replaceAll(" +", " ").trim();
String[] elements = pol.split(" ");
Answer a = new Answer();
for(String e : elements){
System.out.println("element: '" + e + "'");
try {
int value = Integer.parseInt(e);
a.push(value);
} catch(Exception exception) {
a.op(e);
}
}
if(a.last!=null && a.last.parent==null){
return a.last.value;
} else {
throw new RuntimeException("dont match");
}
}
}
// for tests to pass
class Aout {
public static String toString(String s){
System.out.println(s);
return s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment