From e7f35ab8dffb7c2efeda42d45a779634c1a6fdb2 Mon Sep 17 00:00:00 2001 From: Manmeet Singh Date: Mon, 2 Oct 2017 00:42:20 +0530 Subject: [PATCH 1/2] Postfix Notation using Stack Note- Give input in the form like "1 21 + 45 13 + *" #96 --- Misc/StackPostfixNotation | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Misc/StackPostfixNotation diff --git a/Misc/StackPostfixNotation b/Misc/StackPostfixNotation new file mode 100644 index 000000000..c04b0ac6b --- /dev/null +++ b/Misc/StackPostfixNotation @@ -0,0 +1,38 @@ +import java.util.*; + +public class Postfix { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +" + System.out.println(postfixEvaluate(post)); + } + + // Evaluates the given postfix expression string and returns the result. + public static int postfixEvaluate(String exp) { + Stack s = new Stack (); + Scanner tokens = new Scanner(exp); + + 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(); + + 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); + } + + // "+", "-", "*", "/" + } + } + return s.pop(); + } +} From ae3342fb50eb5f4a2b973356e8685fb3ac57543a Mon Sep 17 00:00:00 2001 From: Manmeet Singh Date: Tue, 3 Oct 2017 16:51:42 +0530 Subject: [PATCH 2/2] Added Extension --- Misc/{StackPostfixNotation => StackPostfixNotation.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Misc/{StackPostfixNotation => StackPostfixNotation.java} (100%) diff --git a/Misc/StackPostfixNotation b/Misc/StackPostfixNotation.java similarity index 100% rename from Misc/StackPostfixNotation rename to Misc/StackPostfixNotation.java