Skip to content

Instantly share code, notes, and snippets.

@pavelnganpi
Created July 19, 2014 19:47
Show Gist options
  • Save pavelnganpi/8bf8736ebca6c9dd10e3 to your computer and use it in GitHub Desktop.
Save pavelnganpi/8bf8736ebca6c9dd10e3 to your computer and use it in GitHub Desktop.
convert an infix expression to postfix
package test;
import java.util.Stack;
public class InfixToPostfix {
//checks for the priority of an operator
public static int priority(char ch){
switch(ch){
case '^':
return 5;
case '*':
return 4;
case '/':
return 3;
case '+':
return 2;
case '-':return 1;
}
return -1;
}
//method to check if a character is an operand
public static boolean isOperand(char op){
return (op>='a' && op<='z' || op>='A' && op<='Z');
}
//solution
public static String solution(String infix){
if(infix == null || infix == ""){
return "invalif data";
}
Stack<Character> stack = new Stack<Character>();
String output = "";
//scan through list and use each character
for(int i=0; i < infix.length(); i++){
//checks if character is an operand, if it is
//it puts it in the output string
if(isOperand(infix.charAt(i))){
output+=infix.charAt(i);
}
// if character is ( , push it into stack
else if(infix.charAt(i) == '('){
stack.push(infix.charAt(i));
}
//if character is ) it pops every character in
//stack uptil ( to the ouput string
//then removes (
else if(infix.charAt(i) == ')'){
while(!stack.isEmpty() && stack.peek()!='('){
output += stack.pop();
}
if(stack.isEmpty()){
return "ivalid expression";
}
else{
stack.pop();
}
}
else{
while(!stack.isEmpty() && priority(infix.charAt(i))<priority(stack.peek())){
output+=stack.pop();
//System.out.println("dff");
}
stack.push(infix.charAt(i));
//output +=stack.pop();
//System.out.println(stack.peek());
}
}
while(!stack.isEmpty()){
output+=stack.pop();
}
return output;
}
public static void main(String[]args){
String test = "a+b*(c^d-e)^(f+g*h)-i";
//solution(test);
System.out.println(solution(test));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment