class Zasobnik { private class ZPolozka { int hodnota; ZPolozka dalsi; public ZPolozka(int hodnota, ZPolozka dalsi) { this.hodnota = hodnota; this.dalsi = dalsi; } } private ZPolozka vrchol; public Zasobnik() { this.vrchol = null; } public void Push(int hodnota) { this.vrchol = new ZPolozka(hodnota, this.vrchol); } public int Pop() { int hodnota = this.vrchol.hodnota; this.vrchol = this.vrchol.dalsi; return hodnota; } public boolean isEmpty() { return (this.vrchol == null); } public void PushCommand(char command, int cislo) { if (command=='+') this.Push(this.Pop()+this.Pop()); else if (command=='-') this.Push(this.Pop()-this.Pop()); else if (command=='*') this.Push(this.Pop()*this.Pop()); else if (command=='/') this.Push(this.Pop()/this.Pop()); else this.Push(cislo); } } class Strom { class SPrvek { SPrvek levy; SPrvek pravy; String commands = new String(""); char operator = ' '; int number = 0; public SPrvek(String commands) { this.commands = commands; } } SPrvek vrchol; public Strom(String commands) { this.vrchol = new SPrvek(commands); } public void parsuj(SPrvek x) { int cLength = 0; int pZavorek = 0; int sBegin = 0; int sEnd = 0; char znak = ' '; if ((x.commands.indexOf('+')==-1) && (x.commands.indexOf('-')==-1) && (x.commands.indexOf('*')==-1) && (x.commands.indexOf('/')==-1)) { x.number = Integer.parseInt(x.commands); return; } cLength = x.commands.length(); for(int i=cLength-1;i>=0;i--) { if (x.commands.charAt(i)==')') pZavorek++; if (x.commands.charAt(i)=='(') pZavorek--; znak = x.commands.charAt(i); if ((pZavorek==0) && ((znak=='+') || (znak=='-') || (znak=='*') || (znak=='/'))) { sBegin = 0; sEnd = i; if (x.commands.charAt(0)=='(') sBegin++; if (x.commands.charAt(i-1)==')') sEnd--; String lCast = x.commands.substring(sBegin, sEnd); sBegin = i+1; sEnd = cLength; if (x.commands.charAt(i+1)=='(') sBegin++; if (x.commands.charAt(cLength-1)==')') sEnd--; String pCast = x.commands.substring(sBegin, sEnd); char operator = znak; System.out.println(lCast + " a "+pCast + " op: "+operator); x.operator = operator; x.levy = new SPrvek(lCast); x.pravy = new SPrvek(pCast); break; } } this.parsuj(x.levy); this.parsuj(x.pravy); } void postorderR(SPrvek x, Zasobnik zasobnik){ if (x==null) return; this.postorderR(x.levy, zasobnik); this.postorderR(x.pravy, zasobnik); if (x.operator!=' ') { System.out.println(x.operator+" "); } else { System.out.println(x.number+" "); } zasobnik.PushCommand(x.operator, x.number); } public int getValue() { Zasobnik zasobnik = new Zasobnik(); this.postorderR(this.vrchol, zasobnik); if (zasobnik.isEmpty()) return 0; return zasobnik.Pop(); } } public class Cv06Pr3 { public static void main(String[] args) { Strom parser = new Strom("((2+4)*(1+3))+2"); parser.parsuj(parser.vrchol); System.out.println(parser.getValue()); } }