Sirs,
I was assigned the task of doing the Postfixed Infix conversion, however, I'm having some error in my code.
I've debugged, rolled the code and can not find what it is.
I would appreciate it if someone showed me the problem.
The statement follows:
Make the inflection conversion to Postfix.
a) Insert left parenthesis '(' in stack
b) Add right parenthesis ')' at the end of infix.
c) Read each infix character from left to right by doing the following:
-
If the current character in infix is a digit, add it to postfix.
-
If the current infix character is a left parenthesis, add it to the stack.
-
If the current infix character is an operator:
- > Remove the operators from the top of the stack as long as they have precedence greater than or equal to the current operator and add the removed operators to postfix.
- > Insert the current infix character (the operator) into the stack.
- If the current infix character is a right parenthesis:
- > Remove the operators from the top of the stack and add them to postfix until a left parenthesis is at the top of the stack.
- > Remove and discard the left parenthesis of the stack. "
Here's an example:
Infographic notation:
A + B * C
Postfix Notation:
A B C * +
Follow the code below:
private static String convertePosFix(String infix){
Stack<Character> pilha = new ArrayStack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
pilha.push('(');
infix += ')';
for (Character c: infix.toCharArray()) {
if(Character.isDigit(c)){
postfix.append(c);
}else if(c == '('){
pilha.push(c);
}else if(isOperador(c)){
Character top = pilha.top();
while(!pilha.isEmpty() && !isPrecedenciaCurrenteMenorTop(c, top))
postfix.append(pilha.pop());
pilha.push(c);
}else if(c == ')'){
while (!pilha.isEmpty() && pilha.top() != '('){
Character pop = pilha.pop();
postfix.append(pop);
}
}else{
if(c != ' ')
postfix.append(c);
}
}
while (!pilha.isEmpty())
postfix.append(pilha.pop());
return postfix.toString();
}
private static boolean isPrecedenciaCurrenteMenorTop(char currente, char top){
switch (currente)
{
case '+':
case '-':
return !(top == '+' || top == '-');
case '*':
case '/':
return top == '^' || top == '(';
case '^':
return top == '(';
case '(':
return true;
default:
return false;
}
}
private static boolean isOperador(char c){
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(' || c == ')';
}