package Others;import java.util.*;public class StackPostfixNotation {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));scanner.close();}// Evaluates the given postfix expression string and returns the result.public static int postfixEvaluate(String exp) {Stack<Integer> s = new Stack<Integer>();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 operationint 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);}// "+", "-", "*", "/"}}tokens.close();return s.pop();}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。