2019-05-09 19:32:54 +08:00
|
|
|
package Others;
|
|
|
|
|
2017-10-02 03:12:20 +08:00
|
|
|
import java.util.*;
|
|
|
|
|
2017-12-14 10:57:43 +08:00
|
|
|
public class StackPostfixNotation {
|
2017-10-02 03:12:20 +08:00
|
|
|
public static void main(String[] args) {
|
2019-05-09 19:32:54 +08:00
|
|
|
Scanner scanner = new Scanner(System.in);
|
2017-10-02 03:12:20 +08:00
|
|
|
String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +"
|
|
|
|
System.out.println(postfixEvaluate(post));
|
2020-01-29 00:34:52 +08:00
|
|
|
scanner.close();
|
2017-10-02 03:12:20 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Evaluates the given postfix expression string and returns the result.
|
|
|
|
public static int postfixEvaluate(String exp) {
|
2019-05-09 19:32:54 +08:00
|
|
|
Stack<Integer> s = new Stack<Integer>();
|
|
|
|
Scanner tokens = new Scanner(exp);
|
2017-10-02 03:12:20 +08:00
|
|
|
|
2019-05-09 19:32:54 +08:00
|
|
|
while (tokens.hasNext()) {
|
|
|
|
if (tokens.hasNextInt()) {
|
|
|
|
s.push(tokens.nextInt()); // If int then push to stack
|
|
|
|
} else { // else pop top two values and perform the operation
|
|
|
|
int num2 = s.pop();
|
|
|
|
int num1 = s.pop();
|
|
|
|
String op = tokens.next();
|
2017-10-02 03:12:20 +08:00
|
|
|
|
2019-05-09 19:32:54 +08:00
|
|
|
if (op.equals("+")) {
|
|
|
|
s.push(num1 + num2);
|
|
|
|
} else if (op.equals("-")) {
|
|
|
|
s.push(num1 - num2);
|
|
|
|
} else if (op.equals("*")) {
|
|
|
|
s.push(num1 * num2);
|
|
|
|
} else {
|
|
|
|
s.push(num1 / num2);
|
|
|
|
}
|
2017-10-02 03:12:20 +08:00
|
|
|
|
2019-05-09 19:32:54 +08:00
|
|
|
// "+", "-", "*", "/"
|
|
|
|
}
|
|
|
|
}
|
2020-01-29 00:34:52 +08:00
|
|
|
tokens.close();
|
2019-05-09 19:32:54 +08:00
|
|
|
return s.pop();
|
2017-10-02 03:12:20 +08:00
|
|
|
}
|
|
|
|
}
|