重拾编程之路--数据结构--中缀表示法转换成前缀表示法
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)); } */ } }
相关文章推荐
- 重拾编程之路--数据结构--中缀表示法转换成后缀表示法
- 数据结构复习
- 数据结构与算法——归并排序
- opencv 基本数据结构
- 数据结构之稀疏矩阵存储实现
- 学习笔记------数据结构(C语言版) 静态链表
- sunday算法
- 初学循环队列
- BF算法
- IOS-底层数据结构
- Haffman编码/译码——数据结构作业(二)
- 校园导航——数据结构作业(一)
- Java之Pcap文件解析(二:建立数据结构)
- 学数据结构,仅仅须要主要的编程体验
- 数据结构_3:栈:STL
- 数据结构_3:栈:C++
- 数据结构之 数组
- 【Java】Java数据结构和算法(二)——栈和队列
- 数据结构与算法——堆排序
- C语言数据结构——队列