package com.dt.stactt.zhongturntohouzhui;
import java.util.Stack;
/**
* 计算机实现转换:
将中缀表达式转换为后缀表达式的算法思想:
·开始扫描;
·数字时,加入后缀表达式;
·运算符:
a. 若为最高级的运算符,入栈;
b. 若为 '(',入栈;
c. 若为 ')',则依次把栈中的的运算符加入后缀表达式中,直到出现'(',从栈中删除'(' ;
d. 若为不是最高级的运算符,则将从栈顶到第一个优先级不大于(小于,低于或等于)它的运算符(或 '(',但优先满足前一个条件)之间的运算符加入后缀表达式中,该运算符再入栈;
* @author kuwo
*
*/
public class MidleTurnToBehind {
private String testString = null;
private Stack<Character> stack = null;
public MidleTurnToBehind(String str){
this.testString = str;
stack = new Stack<Character>();
}
private void anaysisStr(){
for (int i = 0; i < testString.length(); i++) {
char c = testString.charAt(i);
if (c == '+' || c == '-') {
if (stack.isEmpty() || stack.peek() == '(') {
stack.push(c);
} else {
while (!stack.isEmpty()
&& (stack.peek() == '*' || stack.peek() == '/'
|| stack.peek() == '+' || stack.peek() == '-')) {
System.out.print(stack.pop());
}
stack.push(c);
}
} else if (c == '*' || c == '/') {
if (stack.isEmpty() || stack.peek() == '+'
|| stack.peek() == '-' || stack.peek() == '(') {
stack.push(c);
} else {
while (!stack.isEmpty()
&& (stack.peek() == '/' || stack.peek() == '*')) {
System.out.print(stack.pop());
}
stack.push(c);
}
} else if (c == '(') {
stack.push(c);
} else if (c == ')') {
char temp = ' ';
while ((temp = stack.pop()) != '(') {
System.out.print(temp);
}
} else {
System.out.print(c);
}
}
if (!stack.isEmpty()) {
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
}
private void anaysis(){
for (int i = 0; i < testString.length(); i++) {
char c = testString.charAt(i);
if(c == '+' || c == '-'){
if(stack.isEmpty() || stack.peek() == '('){
// 当栈是空的时候,运算符可以直接入栈
stack.push(c);
}else{
// 当栈不为空的时候,就把优先级不大于(包括等于)当前运算符的内容输出
while (!stack.isEmpty() && (stack.peek() == '*'
|| stack.peek() == '/' || stack.peek() == '+' || stack.peek() == '-')) {
System.out.print(stack.pop());
}
// 将此运算符之前的运算符出栈,之后当前运算符就要入栈。
stack.push(c);
}
}else if(c == '*' || c == '/'){
if(stack.isEmpty() || stack.peek() == '+' || stack.peek() == '-'){
stack.push(c);
}else {
while((!stack.isEmpty() && (stack.peek() == '/' || stack.peek() == '*'))){
System.out.print(stack.pop());
}
stack.push(c);
}
}else if(c == '('){
// 'c'运算符是优先级最高的运算符,只要出现这个运算符就要入栈
stack.push(c);
}else if(c == ')'){
// 如果出现了')'运算符则要把'('运算符之后的所以的运算符出栈
char temp;
while ((temp = stack.peek()) != '(') {
System.out.print(temp);
}
}else{
// 如果当前字符不是运算符,则直接输出
System.out.print(c);
}
}
if (!stack.isEmpty()) {
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
}
public static void main(String[] args) {
// MidleTurnToBehind testStacknew = new MidleTurnToBehind("A+B*(C-D)/E+F/H");
// MidleTurnToBehind testStacknew = new MidleTurnToBehind("a+b*c+(d*e+f)*g");
MidleTurnToBehind testStacknew = new MidleTurnToBehind("a-b-c");
// MidleTurnToBehind testStacknew = new MidleTurnToBehind("ac");
// testStacknew.anaysisStr();
testStacknew.anaysis();
}
}
栈应用之中缀和后缀
最新推荐文章于 2022-01-17 17:31:52 发布