Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- public class Source {
- public static void main(String[] args) {
- }
- static String infix_to_reverse_polish(String infix) {
- final String ops = "=|&?<>-+/*^!~()";
- StringBuilder sb = new StringBuilder();
- Stack<Integer> s = new Stack<>();
- for (int i = 0; i < infix.length(); i++) {
- String current = new String("" + infix.charAt(i));
- System.out.println(current);
- if (current.isEmpty())
- continue;
- char c = current.charAt(0);
- int idx = ops.indexOf(c);
- if (idx != -1) {
- if (s.isEmpty())
- s.push(idx);
- else {
- while (!s.isEmpty()) {
- int prec2 = s.peek();
- int prec1 = idx ;
- if (prec2 > prec1 || (prec2 == prec1 && c != '^' && c != '!' && c != '~'))
- sb.append(ops.charAt(s.pop())).append(' ');
- else break;
- }
- s.push(idx);
- }
- }
- else if (c == '(') {
- s.push(-2);
- }
- else if (c == ')') {
- if(s.size() == 0) {
- return "e r r o r";
- }
- while (s.peek() != -2)
- sb.append(ops.charAt(s.pop())).append(' ');
- s.pop();
- }
- else {
- sb.append(current).append(' ');
- }
- }
- while (!s.isEmpty())
- sb.append(ops.charAt(s.pop())).append(' ');
- return sb.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement