你能解释一下如何添加吗?
我的中缀是:1^2+3/3
前缀表达式是:(+1^2/33
这是错误的)
后缀表达式是:(1^233/+
这是错误的)
前缀将是:+^12/33
后缀将是:12^33/+
我的代码:
import java.io.*;
class Stack
{
private char[] a;
private int top,m;
public Stack(int max)
{
m=max;
a=new char[m];
top=-1;
}
public void push(char key)
{
a[++top]=key;
}
public char pop()
{
return(a[top--]);
}
public char peek()
{
return(a[top]);
}
public boolean isEmpty()
{
return (top==-1);
}
}
class Evaluation
{
private Stack s;
private String input;
private String output="";
public Evaluation(String str)
{
input=str;
s=new Stack(str.length());
}
public String inToPre()
{
for(int i=input.length()-1;i>=0;i--)
{
char ch=input.charAt(i);
**switch(ch)
{
case '+':
case '-':gotOperator(ch,1,')');
break;
case '*':
case '/':gotOperator(ch,2,')');
break;
case ')':s.push(ch);
break;
case '(':gotParenthesis(')');
break;
default:output=ch+output;
}
}
while(!s.isEmpty())
output=s.pop()+output;
return output;
} // End to inToPre
public String inToPost()
{
for(int i=0;i<input.length();i++)
{
char ch=input.charAt(i);
switch(ch)
{
case '+':
case '-':gotOperator(ch,1,'(');
break;
case '*':
case '/':gotOperator(ch,2,'(');
break;
case '(':s.push(ch);
break;
case ')':gotParenthesis('(');
break;
default:output=output+ch;
}
}
while(!s.isEmpty())
output=output+s.pop();
return output;
} // End inToPost**
private void gotOperator(char opThis,int prec1,char x)
{
while(!s.isEmpty())
{
char opTop=s.pop();
if(opTop==x)
{
s.push(opTop);
break;
}
else
{
int prec2;
if(opTop=='+'||opTop=='-')
prec2=1;
else
prec2=2;
if(prec2<prec1&&x=='(')
{
s.push(opTop);
break;
}
else if(prec2<=prec1&&x==')')
{
s.push(opTop);
break;
}
else
{
if(x==')')
output=opTop+output;
else
output=output+opTop;
}
}
} // End While gotOperator
s.push(opThis);
} // End gotOperator
private void gotParenthesis(char x)
{
while(!s.isEmpty())
{
char ch=s.pop();
if(ch==x)
break;
else
{
if(x==')')
output=ch+output;
else
output=output+ch;
} // End Else
} // End While gotParenthesis
} // End gotParenthesis
} // End Class Evaluation