168k views
3 votes
Convert infix to postfix

(Convert infix to postfix)

Note:

Postfix notation is a way of writing expression without using parentheses. For example, the expression ( 11 + 12 ) * 13 would be written as 11 12 + 13 *

Assume that ALWAYS there is a space between operands and operators in the input expression.

Use two stacks, one to store the operands and one to store the operators.

Your program only accpets following operators :

( )

+

-

/

*

Write a method to converts an infix expression into a postfix expression using the following method:

String infixToPostfix(String expression)

For example, the method should convert the infix expression

( 13 + 25 ) * 34 to 13 25 + 34 *

and

20 * ( 10 + 30 ) to 20 10 30 + *.

///////////////////////

import java.util.*;
import java.lang.*;
import java.io.*;

class InfixToPostfix{
public String infixToPostfix(String expression) {

}
}
class DriverMain{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
InfixToPostfix postfix = new InfixToPostfix();
try {
System.out.println(postfix.infixToPostfix(input.nextLine()));
}
catch (Exception ex) {
System.out.println("Wrong expression");
}
}
}

only make change to class infixToPostfix

User Rckrd
by
5.7k points

1 Answer

4 votes

Answer:

static int checkSymbol(char ch)

{

switch (ch)

{

case '+':

case '-':

return 1;

case '*':

case '/':

return 2;

case '^':

return 3;

}

return -1;

}

static String convertInfixToPostfix(String expression)

{

String calculation = new String("");

Stack<Character> operands = new Stack<>();

Stack<Character> operators = new Stack<>();

for (int i = 0; i<expression.length(); ++i)

{

char c = expression.charAt(i);

if (Character.isLetterOrDigit(c))

operands.push(c);

else if (c == '(')

operators.push(c);

else if (c == ')')

{

while (!operators.isEmpty() && operators.peek() != '(')

operands.push(operators.pop());

if (!operators.isEmpty() && operators.peek() != '(')

return NULL;

else

operators.pop();

}

else

{

while (!operators.isEmpty() && checkSymbol(c) <= checkSymbol(operators.peek()))

operands.push(operators.pop());

operators.push(c);

}

}

while (!operators.isEmpty())

operands.push(operators.pop());

while (!operands.isEmpty())

calculation+=operands.pop();

calculation=calculation.reverse();

return calculation;

}

Step-by-step explanation:

  • Create the checkSymbol function to see what symbol is being passed to the stack.
  • Create the convertInfixToPostfix function that keeps track of the operands and the operators stack.
  • Use conditional statements to check whether the character being passed is a letter, digit, symbol or a bracket.
  • While the operators is not empty, keep pushing the character to the operators stack.
  • At last reverse and return the calculation which has all the results.
User Matthias Loibl
by
5.7k points