Elementary data structures - Stack http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_A
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn
object Main extends App {
val inputList = StdIn.readLine().split(" ").map {
str =>
try {
str.toInt
} catch {
case e: NumberFormatException =>
str
}
}.toList
val stack = new Stack
inputList.foreach { elm =>
stack.push(elm)
}
println(stack.pop())
}
class Stack {
val array = ArrayBuffer.empty[Int]
def push(elm: Any): Unit = {
elm match {
case n: Int =>
array += n
case str: String =>
val (o1, o2) = pop2()
str match {
case "+" =>
push(o2 + o1)
case "-" =>
push(o2 - o1)
case "*" =>
push(o2 * o1)
}
}
}
def pop(): Int = {
array.remove(array.length - 1)
}
def pop2(): (Int, Int) = {
(pop(), pop())
}
}
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public Main() {
Scanner scan = new Scanner(System.in);
Stack stack = new Stack(200);
while(scan.hasNext()){
String str = scan.next();
stack.push(str);
}
System.out.println(stack.pop());
}
public static void main(String[] args) {
new Main();
}
private class Stack{
private int top = 0;
private int stack[];
public Stack(int size){
stack = new int[size];
}
public void push(int n){
stack[top++] = n;
}
public void push(String str){
if(isInteger(str)){
int n = Integer.parseInt(str);
push(n);
}else{
int o1 = pop();
int o2 = pop();
if(str.equals("+")){
push(o2+o1);
}
else if(str.equals("-")){
push(o2-o1);
}else{
push(o2*o1);
}
}
}
public int pop(){
return stack[--top];
}
public boolean isInteger(String str) {
try {
Integer.parseInt(str);
} catch(NumberFormatException e) {
return false;
}
return true;
}
}
}