1. Ask the user for an infix expression. Assume the expression is valid. 2. If the expression...
Question:
1. Ask the user for an infix expression. Assume the expression is valid.
2. If the expression is empty, then stop running. otherwise
3. Convert the infix expression to a postfix expression.
4. Repeat from 1
*The expression can contain numbers, +, -, /, *, '(', ')', '{','}' and space(s)
*Use HashMap to find the precedence of each operator.
To convert Infix Expression into Postfix Expression using a stack data structure
1. Read all the symbols one by one from left to right in the given Infix Expression.
2. If the token is operand, then directly add it to the result (postfix).
3. If the token is '(', '{' then Push it onto the Stack.
4. If the token is ')', '}'
• Pop all the contents of stack until respective '(' or '{' is popped and add each poped symbol to the result (postfix).
• '(' and '{' are not added to the postfix.
5. If the token is operator (+ , - , * , /)
• If top of the stack is '(' or '{', OR statck is empty, push it.
• else, pop the operators that are already on the stack that have higher or equal precedence than the token, and add them to
the postfix. After that, Push the token.
6. After reading all the symbols, pop all the elements and add them to the postfix.
expression (Use this class as is
static Scanner input = new Scanner(System.in);
static String infix;
static String postfix;
public static void main(String[] args) {
while (true) {
System.out.println();
System.out.println("Enter an infix expression");
infix = input.nextLine();
if (infix.length()==0) {
System.out.println("Bye..");
break;
}
else {
InfixToPostfix i2p = new InfixToPostfix();
postfix = i2p.infix2postfix(infix);
System.out.println("infix: " + infix );
System.out.println("postfix: " + postfix );
}
}
}
InfixToPostfix
public static String post = "";
public static HashMap precedence = new HashMap<>();
public String infix2postfix(String infix) {
loadPrecedence();
Stack stack = new Stack();
post = "";
for (int j=0; jchar c = infix.charAt(j);
if (c>='0' && c<='9') {
. . .
}
if(c == '(' || c == '{') {
. . .
}
Data Structures And Algorithms In C++
ISBN: 9780470383278
2nd Edition
Authors: Michael T. Goodrich, Roberto Tamassia, David M. Mount