代码是错误的,NND!!,如果是高手,就改下吧。
用栈和后缀表达式来求解
栈
package endual.iteye.com.main;
public class StackX {
private char[] arrays = null ;
private int maxSize ;
private int top ;
public StackX(int maxSize) {
this.arrays = new char[maxSize] ;
maxSize = maxSize;
this.top = 0 ;
}
//默认是在正常的范围内
public void push (char newChar) {
this.arrays[top] = newChar ;
this.top++ ;
}
//上面那个给弄出来
public char pop () {
char topChar = 'x' ;
topChar = this.arrays[top-1] ;
top-- ;
return topChar ;
}
//获取栈的个数
public int getLength() {
return this.top ;
}
//判断栈是否为空
public boolean isFull() {
if (this.getLength() == 0) {
return false ;
}
return true ;
}
}
运行类:
package endual.iteye.com.main;
public class MainTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
test();
}
private static void test() {
String _s = "3-(5+4)" ;
char[] arrs = _s.toCharArray() ;
int maxSize = arrs.length ;
int nLabel = 0 ;
for (int i=0; i<maxSize; i++) {
if (isLabel(arrs[i])) {
nLabel++ ;
}
}
StackX stack = new StackX(nLabel) ;
String _ans = "" ;
for (int i=0; i<maxSize; i++) {
char newChar = arrs[i] ; //读取字符
//判断该字符不是运算符
if (isLabel(newChar)) {
//判断栈是否为空
if (!stack.isFull() || isLabel(newChar) || isLeft(newChar)) { //如果站为空了
stack.push(newChar) ;
} else { //如果站不为空,那么就跳出来一个一个字符
if (stack.isFull() ) { //如果栈有东西
if (isLeft(newChar)) { // 如果是左括号,加入到栈去
stack.push(newChar) ;
continue ; // 终止,下一轮
}
//判断该跳出来的字符是与当前的字符进行比较
if (isRight(newChar)) { //那么要弹出了
char topChar = stack.pop() ;
while (topChar == '(') {
_ans = _ans + topChar ;
topChar = stack.pop() ;
}
continue ;
}
char topChar = stack.pop() ;
//那么剩余的就是减号或者加号了
_ans = _ans + topChar ;
stack.push(newChar) ;
}
else { //如果站为空
}
}
}
else { //如果不是运算符号
_ans = _ans + newChar ;
}
} // for
while (stack.isFull()) {
char topChar = stack.pop() ;
_ans = _ans + topChar ;
}
System.out.println(_ans);
}
public static boolean isHighClass(char newChar) {
if ('/' == newChar) {
return true ;
}
if ('*' == newChar) {
return true ;
}
return false ;
}
public static boolean isLeft(char newChar) {
if ('(' == newChar) {
return true ;
}
return false ;
}
public static boolean isRight(char newChar) {
if (')' == newChar) {
return true ;
}
return false ;
}
//判断是否是运算符号
public static boolean isLabel(char newChar) {
if ('-' == newChar) {
return true ;
}
if ('+' == newChar) {
return true ;
}
if ('/' == newChar) {
return true ;
}
if ('*' == newChar) {
return true ;
}
if ('(' == newChar) {
return true ;
}
if (')' == newChar) {
return true ;
}
return false ; //不是运算符
}
}

被折叠的 条评论
为什么被折叠?



