Skip to content

Instantly share code, notes, and snippets.

@kaldas
Created August 25, 2011 18:38
Show Gist options
  • Save kaldas/1171418 to your computer and use it in GitHub Desktop.
Save kaldas/1171418 to your computer and use it in GitHub Desktop.
/* GEC2010N-05 / JAVA III
* Prof. Tomás de Aquino Tinoco Botelho
*/
package trabjava31;
/**
* @author EQUIPE ROCKET w/ much help of Deitel and internet!
*/
import java.util.*;
public class NotationConverter {
public String convertToPostfix(String inFix)
{
String outFix = "";
Stack<String> memStack = new Stack<String>();
String ch = "";
for(int pos = 0;pos != inFix.length();pos++)
{
ch = inFix.substring(pos, pos + 1);
if(ch.matches("[a-zA-Z]|\\d"))
{
outFix += ch;
}
else if(isOperator(ch))
{
if(memStack.isEmpty())
{
memStack.push(ch);
}
else
{
String stackTop = memStack.peek();
while (getPrecedence(ch,stackTop) && !(memStack.isEmpty()))
{
outFix += memStack.pop();
if(!(memStack.isEmpty()))
stackTop = memStack.peek();
}
memStack.push(ch);
}
}
}
while(!(memStack.isEmpty()))
outFix += memStack.pop();
return outFix;
}
private boolean isOperator(String ch)
{
if(ch.equals("+") || ch.equals("-") || ch.equals("*") ||
ch.equals("/") || ch.equals("^"))
{
return true;
}
return false;
}
private boolean getPrecedence(String newOperator, String oldOperator)
{
if (newOperator.equals("^"))
return true;
else if (oldOperator.equals("^") )
return false;
else if (newOperator.equals("*") || newOperator.equals("/"))
return true;
else if (newOperator.equals("+") || newOperator.equals("-"))
{
if (oldOperator.equals("*") || oldOperator.equals("/"))
return false;
else
return true;
}
return false;
}
}
/* end of homework */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment