Algorithm:
for each expression token:
if the token is a number:
add it to output
else if the token is a left paren:
push it
else if the token is a right paren:
pop and add to output all tokens on stack up to left paren
pop the left paren, but don't add to output
else if the token is an operator:
if stack is empty or the top is a left paren:
push it
else if the stack top is a lower precedence operator:
push it
else
pop and add to output all operators of higher or equal precedence
push it
when there are no more tokens,
pop and add to output all remaining operators on stack
Example:
7 - 3 + 5 - 2
token stack output
----- ----- ------
[]
7 7
- [-]
3 7 3
+ [+] 7 3 -
5 7 3 - 5
- [-] 7 3 - 5 +
2 7 3 - 5 + 2
END [] 7 3 - 5 + 2 -
Code:
import java.util.*;
public class InfixToPostfix {
// Translate's the expression to postfix
public static String translate(String expression) {
String output = "";
char character = ' ';
Stack<Character> stack = new Stack<Character>();
for (int x = 0; x < expression.length(); x++) {
character = expression.charAt(x);
if (isOperator(character)) {
while (!stack.empty()
&& precedence(stack.peek()) >= precedence(character))
output += stack.pop() + " ";
stack.push(character);
} else if (character == '(') {
stack.push(character);
} else if (character == ')') {
while (!stack.peek().equals('('))
output += stack.pop() + " ";
stack.pop();
} else {
output += character;
}
}
while (!stack.empty()) {
output += stack.pop() + " ";
}
return output;
}
// Check priority on characters
public static int precedence(char operator) {
if (operator == '+' || operator == '-')
return 1;
else if (operator == '*' || operator == '/')
return 2;
else
return 0;
}
public static boolean isOperator(char element) {
if (element == '*' || element == '-' || element == '/'
|| element == '+')
return true;
else
return false;
}
public static void main(String args[])
{
System.out.println("Postfix conversion"+InfixToPostfix.translate("((2 * 3) - 5) / 4"));
}
}
No comments:
Post a Comment