Created
February 14, 2015 05:55
-
-
Save ababup1192/e32502f6aa32ae67ccab to your computer and use it in GitHub Desktop.
Elementary data structures - Stack http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_A
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment