栈-中缀表达式换成后缀

package c_stack.C_Infix;


/**
 * @author Administrator 中缀表达式换成后缀
 */
public class InfixApp {
public static void main(String[] args) {
String input = " 3 + 4 - 6 / 2 * (6 + 3 * (4 - 1))";

InToPost theIt = new InToPost(input);
String result = theIt.doTrans();
System.out.println(result);
}
}package c_stack.C_Infix;


public class InToPost {
StackX theStackX;
String input;
String output = "";


public InToPost(String in) {
input = in;
int stackSize = in.length();
theStackX = new StackX(stackSize);
}


public String doTrans() {
for (int i = 0; i < input.length(); i++) {
char choice = input.charAt(i);
switch (choice) {
case '+':
case '-':
getOper(choice, 1);
break;
case '*':
case '/':
getOper(choice, 2);
break;
case '(':
theStackX.push(choice);
break;
case ')':
gotPraen(choice);
break;
default:// 必须是操作数,累加
output += choice;
break;
}


}
while (!theStackX.isEmpty()) {
output += theStackX.pop();
}
return output;
}


private void gotPraen(char ch) {
// 弹出所有数据项,当是(时结束循环
while (!theStackX.isEmpty()) {
char opTop = theStackX.pop();
if (opTop == '(')
break;
else {
output += opTop;
}
}


}


private void getOper(char opThis, int prec1) {
// 防止弹出的结束的不止一个,shile
// 不管怎样操作都会入栈,提出来放后面
while (!theStackX.isEmpty()) {
char opTop = theStackX.pop();
// 当出栈的是(时,放入,并结束循环
if (opTop == '(') {
theStackX.push(opTop);
break;
} else {// 判断运算符优先级,小于则在放回栈中,大于则弹出。进行下一次循环判断
int prec2;
if (opTop == '+' || opTop == '-')
prec2 = 1;
else
prec2 = 2;
if (prec2 < prec1) {
theStackX.push(opTop);
break;
}
output += opTop;
}
}
theStackX.push(opThis);
}


}package c_stack.C_Infix;


public class StackX {
private char arr[];
private int top;
private int maxSize;


public StackX(int s) {
maxSize = s;
arr = new char[maxSize];
top = -1;
}


public void push(char key) {
arr[++top] = key;


}


public char pop() {
return arr[top--];
}


public char peek() {
return arr[top];
}


public char peekN(int n) {
return arr[n];
}


public boolean isEmpty() {
return top == -1;
}


public boolean isFull() {
return top == maxSize - 1;
}


public int size() {
return top + 1;
}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值