Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

December 27, 2009

Infix to Postfix - Java Program

import java.util.LinkedList;
import java.util.Stack;

public class InfixtoPostfix {

static Stack inputStack;

static String output = "";

public static void main(String[] args) {
String input = "1+2*4/5-7+3/6";

System.out.println(infixToPostfix(input));

}

public static String infixToPostfix(String input) {

inputStack = new Stack();

for (int i = 0; i < input.length(); i++) {
char current = input.charAt(i);
if (current == '+' || current == '-') {
isOperator(current, 1);
} else if (current == '*' || current == '/') {
isOperator(current, 2);
} else {
output += current;
}
}
while(!inputStack.isEmpty()){
char top = (Character) inputStack.pop();
output += top;
}
return output;
}

public static void isOperator(char c, int prec) {
while (!inputStack.isEmpty()) {
char top = (Character) inputStack.pop();
int topPrec = 0;
if (top == '+' || top == '-') {
topPrec = 1;
} else {
topPrec = 2;
}

if (topPrec >= prec) {
output += top;
}else{
inputStack.push(top);
break;
}

}
inputStack.push(c);
}

}

No comments: