Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class PostFix {
- public LinkedList<String> inFix;
- public LinkedList<String> postFix;
- public static void main(String[] args) {
- PostFix test = new PostFix();
- test.inFix = new LinkedList<String>();
- test.inFix.add("2.1");
- test.inFix.add("/");
- test.inFix.add("3.2");
- test.inFix.add("-");
- test.inFix.add("(");
- test.inFix.add("6.3");
- test.inFix.add("-");
- test.inFix.add("4.2");
- test.inFix.add(")");
- // === For testing ===
- //while (!test.inFix.isEmpty()) System.out.print(test.inFix.remove());
- test.inFixToPostFix();
- // === For testing ===
- //while (!test.postFix.isEmpty()) System.out.print(test.postFix.remove() + " ");
- }
- public static boolean isoperator(String arg) {
- return arg.equals("+") || arg.equals("-") || arg.equals("*") || arg.equals("/") || arg.equals("(") || arg.equals(")");
- }
- public void inFixToPostFix() {
- if (inFix == null)
- return;
- // create ranking
- HashMap<String, Integer> rank = new HashMap<String, Integer>();
- rank.put("*", 2);
- rank.put("/", 2);
- rank.put("+", 1);
- rank.put("-", 1);
- postFix = new LinkedList<String>();
- LinkedList<String> operatorStack = new LinkedList<String>();
- while (!inFix.isEmpty()) {
- String curr = inFix.remove();
- if (!isoperator(curr))
- {
- postFix.add(curr);
- } else if (curr.equals("(")) {
- operatorStack.push(curr);
- } else if (curr.equals(")")) {
- while (!operatorStack.peek().equals("(")) {
- postFix.add(operatorStack.pop());
- }
- operatorStack.remove(); // remove "("
- } else { // it's an operator +,-,*,/
- int currRank = rank.get(curr);
- if (!operatorStack.isEmpty() && !operatorStack.peek().equals("(") && rank.get(operatorStack.peek()) >= currRank) {
- while (!operatorStack.isEmpty() && rank.get(operatorStack.peek()) >= currRank) {
- postFix.add(operatorStack.pop());
- }
- }
- operatorStack.add(curr);
- }
- }
- while (!operatorStack.isEmpty()) {
- postFix.add(operatorStack.pop());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement