0% found this document useful (0 votes)
4 views2 pages

DSJ pgm4

Uploaded by

janakirampilli70
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

DSJ pgm4

Uploaded by

janakirampilli70
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

4.

Write a java program that reads an infix expression, converts the expression to postfix form
and then evaluates the postfix expression (use stack ADT).

class InfixToPostfix {

java.util.Stack<Character> stk = new java.util.Stack<Character>();

public String toPostfix(String infix){


infix = "(" + infix + ")"; // enclose infix expr within parentheses
String postfix = "";
/* scan the infix char-by-char until end of string is reached */
for( int i=0; i<infix.length(); i++){
char ch, item;
ch = infix.charAt(i);
if( isOperand(ch) ) // if(ch is an operand), then
postfix = postfix + ch; // append ch to postfix string
if( ch == '(' ) // if(ch is a left-bracket), then
stk.push(ch); // push onto the stack
if( isOperator(ch) ) // if(ch is an operator), then
{
item = stk.pop(); // pop an item from the stack
/* if(item is an operator), then check the precedence of ch and item*/
if( isOperator(item) ) {
if( precedence(item) >= precedence(ch) ){
stk.push(item);
stk.push(ch);
}
else{
postfix = postfix + item;
stk.push(ch);
}
}
else {
stk.push(item);
stk.push(ch);
}
} // end of if(isOperator(ch))
if( ch == ')' ) {
item = stk.pop();
while( item != '(' ){
postfix = postfix + item;
item = stk.pop();
}
}
} // end of for-loop
return postfix;
} // end of toPostfix() method
public boolean isOperand(char
c) { return(c >= 'A' && c
<= 'Z');
}
public boolean isOperator(char c){
return( c=='+' || c=='-' || c=='*' || c=='/' );
}

public int precedence(char


c) { int rank = 1; // rank
= 1 for '*‟ or '/'
if( c == '+' || c == '-' ) rank
= 2; return rank;
}
}

class InfixToPostfixDemo

{
public static void main(String args[]){
InfixToPostfix obj = new
InfixToPostfix(); String infix =
"A*(B+C/D)-E";
System.out.println("infix: " + infix );
System.out.println("postfix:"+obj.toPostfix(infix));
}
}

Output:
infix: A*(B+C/D)-E
postfix:
ABCD/+*E-

You might also like