Skip to content

Commit e7f35ab

Browse files
authored
Postfix Notation using Stack
Note- Give input in the form like "1 21 + 45 13 + *" TheAlgorithms#96
1 parent 8b29c6c commit e7f35ab

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Misc/StackPostfixNotation

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.*;
2+
3+
public class Postfix {
4+
public static void main(String[] args) {
5+
Scanner scanner = new Scanner(System.in);
6+
String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +"
7+
System.out.println(postfixEvaluate(post));
8+
}
9+
10+
// Evaluates the given postfix expression string and returns the result.
11+
public static int postfixEvaluate(String exp) {
12+
Stack<Integer> s = new Stack<Integer> ();
13+
Scanner tokens = new Scanner(exp);
14+
15+
while (tokens.hasNext()) {
16+
if (tokens.hasNextInt()) {
17+
s.push(tokens.nextInt()); // If int then push to stack
18+
} else { // else pop top two values and perform the operation
19+
int num2 = s.pop();
20+
int num1 = s.pop();
21+
String op = tokens.next();
22+
23+
if (op.equals("+")) {
24+
s.push(num1 + num2);
25+
} else if (op.equals("-")) {
26+
s.push(num1 - num2);
27+
} else if (op.equals("*")) {
28+
s.push(num1 * num2);
29+
} else {
30+
s.push(num1 / num2);
31+
}
32+
33+
// "+", "-", "*", "/"
34+
}
35+
}
36+
return s.pop();
37+
}
38+
}

0 commit comments

Comments
 (0)