Skip to content

Instantly share code, notes, and snippets.

@lya79
Created January 30, 2018 09:06
Show Gist options
  • Save lya79/3647ee5f78a305c9bdeaeb8e5a9f74c5 to your computer and use it in GitHub Desktop.
Save lya79/3647ee5f78a305c9bdeaeb8e5a9f74c5 to your computer and use it in GitHub Desktop.
簡易版本的後序計算程式,應用堆疊(Stack)資料結構。
import java.util.Arrays;
import java.util.Stack;
import java.util.regex.Pattern;
/*
* 簡易版本的後序計算程式,應用堆疊(Stack)資料結構。
*/
public class StackExample {
public static void main(String[] args) {
/*
* 中序:((1+2)*(3+4))
* 後序:12+34+*
* 計算結果:21
*/
calculatorPostfix(new String[] { "1", "2", "+", "3", "4", "+", "*" });
}
/**
* 以後序進行計算
*
* @param postfix
*/
private static void calculatorPostfix(String[] postfix) {
Stack<String> stack = new Stack<String>();
for (int i = 0; i < postfix.length; i++) {
String token = String.valueOf(postfix[i]);
boolean operand = Pattern.matches("[0-9]", token);
if (operand) {
stack.push(token);
continue;
}
String x = stack.pop();
String y = stack.pop();
if ("+".equals(token)) {
String z = String.valueOf(Integer.parseInt(x) + Integer.parseInt(y));
stack.push(z);
} else if ("-".equals(token)) {
String z = String.valueOf(Integer.parseInt(x) - Integer.parseInt(y));
stack.push(z);
} else if ("*".equals(token)) {
String z = String.valueOf(Integer.parseInt(x) * Integer.parseInt(y));
stack.push(z);
} else if ("/".equals(token)) {
String z = String.valueOf(Integer.parseInt(x) / Integer.parseInt(y));
stack.push(z);
}
}
System.out.println("input: " + Arrays.toString(postfix));
System.out.println("output: " + stack.pop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment