Just another update
This commit is contained in:
parent
a25938f123
commit
00a190b0a6
6591 changed files with 94363 additions and 23227 deletions
|
|
@ -0,0 +1,46 @@
|
|||
import java.util.Stack;
|
||||
|
||||
public class ShuntingYard {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
|
||||
System.out.printf("infix: %s%n", infix);
|
||||
System.out.printf("postfix: %s%n", infixToPostfix(infix));
|
||||
}
|
||||
|
||||
static String infixToPostfix(String infix) {
|
||||
final String ops = "-+/*^";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Stack<Integer> s = new Stack<>();
|
||||
|
||||
for (String token : infix.split("\\s")) {
|
||||
char c = token.charAt(0);
|
||||
int idx = ops.indexOf(c);
|
||||
if (idx != -1 && token.length() == 1) {
|
||||
if (s.isEmpty())
|
||||
s.push(idx);
|
||||
else {
|
||||
while (!s.isEmpty()) {
|
||||
int prec2 = s.peek() / 2;
|
||||
int prec1 = idx / 2;
|
||||
if (prec2 > prec1 || (prec2 == prec1 && c != '^'))
|
||||
sb.append(ops.charAt(s.pop())).append(' ');
|
||||
else break;
|
||||
}
|
||||
s.push(idx);
|
||||
}
|
||||
} else if (c == '(') {
|
||||
s.push(-2);
|
||||
} else if (c == ')') {
|
||||
while (s.peek() != -2)
|
||||
sb.append(ops.charAt(s.pop())).append(' ');
|
||||
s.pop();
|
||||
} else {
|
||||
sb.append(token).append(' ');
|
||||
}
|
||||
}
|
||||
while (!s.isEmpty())
|
||||
sb.append(ops.charAt(s.pop())).append(' ');
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue