您的位置:首页 > 理论基础 > 数据结构算法

重拾编程之路--数据结构--中缀表示法转换成前缀表示法

2016-01-11 19:58 706 查看
package com.lulu.leetcode;

import java.util.Stack;

public class C_PrefixToSufix {

/**
* 中缀表达式转前缀表达式的方法: 从右向左遍历 1.遇到操作数:直接输出(添加到前缀缀表达式中) 2.栈为空时,遇到运算符,直接入栈
* 3.遇到右括号:将其入栈 4.遇到左括号:执行出栈操作,并将出栈的元素输出,直到弹出栈的是右括号,左括号不输出。
* 5.遇到其他运算符:加减乘除:弹出所有优先级小于该运算符的栈顶元素,然后将该运算符入栈 6.最终将栈中的元素依次出栈,输出。
*
* @param args
*/
public String tran(String infix) {
if (infix == null) {
return null;
}
String string = "";
Stack<Character> re_stack = new Stack<>();
Stack<Character> stack = new Stack<>();
int len = infix.length();
for (int i = len - 1; i >= 0; i--) {
char ch = infix.charAt(i);
System.out.println("--" + ch);
if (isDigt(ch)) {
re_stack.push(ch);
System.out.println("dig--" + ch);
} else if (isOperator(ch)) {
while (!stack.empty() && stack.peek() != ')'
&& comparOper(ch, stack.peek()) > 0) {
re_stack.push(stack.pop());
}
stack.push(ch);
System.out.println("opr--" + ch);

} else if (ch == ')') {
stack.push(ch);

} else if (ch == '(') {
while (!stack.empty()) {
char c = stack.pop();
if (c == ')') {
break;
} else {
re_stack.push(c);
System.out.println("(--" + ch);
}
}

} else {
//
}

}
while (!stack.empty()) {
re_stack.push(stack.pop());
}

while (!re_stack.empty()) {
string = string + re_stack.pop();
}
for (int i = 0; i < string.length(); i++) {
System.out.print(string.charAt(i));
}
System.out.println();
return string;
}

public boolean isDigt(char c) {
String string = c + "";
if (string.matches("[0-9]|[a-z]")) {
return true;
} else
return false;
}

public boolean isOperator(char c) {
String string = c + "";
if (string.matches("\\+|\\-|\\*|\\/")) {
return true;
} else
return false;
}

public int comparOper(char op1, char op2) {// 比较运算符的优先级
char c = op1;
switch (c) {
case '+':
case '-':
if (op2 == '*' || op2 == '/') {
return -1;
} else {
return 0;
}
case '*':
case '/':

if (op2 == '+' || op2 == '-') {
return 1;
} else
return 0;

}
return 0;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
C_PrefixToSufix c_InfixToSufix = new C_PrefixToSufix();
String string = "1+((2+3)*4)-5";
// Stack<Character> re_stack = new Stack<>();

String fString = c_InfixToSufix.tran(string);
/*
* for(int i=fString.length()-1;i>=0;i--){
* System.out.print(fString.charAt(i)); }
*/

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: