正在开发将中缀符号转换为后缀的程序。我让它适用于大多数情况,除非需要字符连接。例如,如果我传入一串数字 (1002+304),它会输出 1, 0, 0, 2, 3, 0, 4, + 而不是 1002, 304, +。
import java.util.*;
public class InfixToPostfix {
private Deque<String> postfix; // Used as a queue of String
private static boolean isOperator(char op)
{
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='^'
||op=='('||op==')')
{
return true;
}
return false;
}
private static boolean lowerEqualPrec(char op1, char op2)
{
boolean flag = false;
if(op1=='+'|| op1=='-')
{
if(op2=='+'||op2=='-'||op2=='*'||op2=='/'||op2=='^')
{
flag= true;
}
}else if(op1=='*' || op1=='/')
{
if(op2=='*'||op2=='/'||op2=='^')
{
flag= true;
}
}else if(op1=='^')
{
flag= false;
}else if(op1=='(')
{
flag= false;
}
return flag;
}
public InfixToPostfix(String infix)
{
for(int i=0; i<infix.length(); i++)
{
if(infix.length() ==0 || infix.charAt(0)==')' ||
infix.charAt(i)=='&' || infix.charAt(infix.length()-1)=='(')
{
throw new IllegalArgumentException();
}
}
postfix = new LinkedList<String>();
Stack<Character> stack = new Stack<Character>();
Character ch;
String digits="";
String letters = "";
for(int i=0; i<infix.length(); i++)
{
ch=infix.charAt(i);
if(ch == ' ')
{
//do nothing
}
if(Character.isDigit(ch))
{
digits=""+ch;
if(i+1 >= infix.length() || !Character.isDigit(infix.charAt(i+1)))
{
digits=digits+"";
}
postfix.add(digits);
}
if(Character.isLetter(ch))
{
letters=ch+"";
postfix.add(letters);
}
if(isOperator(ch))
{
if(ch == ')')
{
if(!stack.isEmpty() && stack.peek() != '(')
{
postfix.add(""+stack.pop());
if(!stack.isEmpty())
{
stack.pop();
}
}
}
else
{
if(!stack.isEmpty() && !lowerEqualPrec(ch, stack.peek()))
{
stack.push(ch);
}
else
{
while(!stack.isEmpty() && lowerEqualPrec(ch, stack.peek()))
{
char pop = stack.pop();
if(ch!='(')
{
postfix.add(pop+"");
}
}
stack.push(ch);
}
}
}
}
while(!stack.isEmpty()&&stack.peek()!='(')
{
postfix.add(stack.pop()+"");
}
System.out.println(postfix);
}
public Iterator<String> iterator()
{
return new PostfixIterator(postfix) ;
}
public static void main(String[] args)
{
InfixToPostfix test = new InfixToPostfix("1002+304");
}
}
对于后缀转换
public static String postfixConversion(String input) {
int i;
String postfix = "";
Stack<Character> stack = new Stack<Character>();
for (i = 0; i < input.length(); i++) {
while (input.charAt(i) == ' ') {
++i;
}
if (Character.isDigit(input.charAt(i))) {
postfix += input.charAt(i);
//if (!Character.isDigit(input.charAt(i+1))) {
postfix += ' ';
//}
}
else if (precedenceLevel(input.charAt(i)) != 0) {
while ((!stack.isEmpty()) && (precedenceLevel(stack.peek()) >= precedenceLevel(input.charAt(i))) && (stack.peek() != '(')) {
postfix += stack.peek();
postfix += ' ';
stack.pop();
}
stack.push(input.charAt(i));
}
else if (input.charAt(i) == '(') {
stack.push(input.charAt(i));
}
else if (input.charAt(i) == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix += stack.peek();
stack.pop();
}
stack.pop();
}
}
while (!stack.isEmpty()) {
postfix += stack.peek();
postfix += ' ';
}
return postfix;
}