逆波兰java代码,逆波兰表达式java
表达式求值 逆波兰表达式算法 java版
表达式求值 逆波兰表达式算法 如下:
为源汇等地区用户提供了全套网页设计制作服务,及源汇网站建设行业解决方案。主营业务为成都网站设计、做网站、源汇网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
import java.util.ArrayList;
import java.util.List;
public class MyStack {
private ListString l;
private int size;
public String top;
public MyStack() {
l = new ArrayListString();
size = 0;
top = null;
}
public int size() {
return size;
}
public void push(String s) {
l.add(s);
top = s;
size++;
}
public String pop() {
String s = l.get(size - 1);
l.remove(size - 1);
size--;
top = size == 0 ? null : l.get(size - 1);
return s;
}
}
import java.util.ArrayList;
import java.util.List;
public class Nbl {
private static MyStack ms1 = new MyStack();//生成逆波兰表达式的栈
private static MyStack ms2 = new MyStack();//运算栈
/**
* 将字符串转换为中序表达式
*/
public static ListString zb(String s) {
ListString ls = new ArrayListString();//存储中序表达式
int i = 0;
String str;
char c;
do {
if ((c = s.charAt(i)) 48 || (c = s.charAt(i)) 57) {
ls.add("" + c);
i++;
} else {
str = "";
while (i s.length() (c = s.charAt(i)) = 48
(c = s.charAt(i)) = 57) {
str += c;
i++;
}
ls.add(str);
}
} while (i s.length());
return ls;
}
/**
* 将中序表达式转换为逆波兰表达式
*/
public static ListString parse(ListString ls) {
ListString lss = new ArrayListString();
for (String ss : ls) {
if (ss.matches("\d+")) {
lss.add(ss);
} else if (ss.equals("(")) {
ms1.push(ss);
} else if (ss.equals(")")) {
while (!ms1.top.equals("(")) {
lss.add(ms1.pop());
}
ms1.pop();
} else {
while (ms1.size() != 0 getValue(ms1.top) = getValue(ss)) {
lss.add(ms1.pop());
}
ms1.push(ss);
}
}
while (ms1.size() != 0) {
lss.add(ms1.pop());
}
return lss;
}
/**
* 对逆波兰表达式进行求值
*/
public static int jisuan(ListString ls) {
for (String s : ls) {
if (s.matches("\d+")) {
ms2.push(s);
} else {
int b = Integer.parseInt(ms2.pop());
int a = Integer.parseInt(ms2.pop());
if (s.equals("+")) {
a = a + b;
} else if (s.equals("-")) {
a = a - b;
} else if (s.equals("*")) {
a = a * b;
} else if (s.equals("\")) {
a = a / b;
}
ms2.push("" + a);
}
}
return Integer.parseInt(ms2.pop());
}
/**
* 获取运算符优先级
* +,-为1 *,/为2 ()为0
*/
public static int getValue(String s) {
if (s.equals("+")) {
return 1;
} else if (s.equals("-")) {
return 1;
} else if (s.equals("*")) {
return 2;
} else if (s.equals("\")) {
return 2;
}
return 0;
}
public static void main(String[] args) {
System.out.println(jisuan(parse(zb("0-8+((1+2)*4)-3+(2*7-2+2)"))));
}
}
java 关于逆波兰表达式的两个题
import java.util.Stack;
/**
* @author wengsh
* @date 2010-6-3 用 输入 (6+5)*(5+5) 测试一下
*/
public class MyDemo {
public static void main(String[] a) {
StackCharacter stack = new StackCharacter();
StringBuffer sb = new StringBuffer();
if (a.length 1) {
System.out.println("参数长度不够");
} else {
String s = a[0].trim();
char[] c = s.toCharArray();
try {
for (int i = 0; i c.length; i++) {
int priority = getPriority(c[i]);
if (priority == -1) { // 如果是数字
sb.append(c[i]); // 输出数字或都字母
} else {
if (stack.isEmpty()) {// 当栈为空时
stack.push(c[i]); // 把字符压入栈
} else {// 当栈为不空时
if (priority == -2) { // 如果是 ')'
while (!stack.isEmpty()
getPriority(stack.peek()) != 8) {
sb.append(stack.pop());// 把'('之上的字符弹出栈并输出
}
stack.pop(); // 栈弹出'('
} else {
// 当要压入栈的字符的优先级小于 等于栈顶字符的优先级且栈顶字符不为'('时
while (!stack.isEmpty()
priority = getPriority(stack.peek())
getPriority(stack.peek()) != 8) {
sb.append(stack.pop()); // 弹出栈顶字符并输出
}
stack.push(c[i]);// 将此时的字符压入栈顶
}
}
}
}
// 读到输入末尾
while (!stack.isEmpty()) {
sb.append(stack.pop()); // 弹出栈中所有元素并输出
}
System.out.println(sb); // 结果 65+55+*
System.out.println(calstack(sb.toString()));//结果 110.0
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获得字符串优先级如果字符不在给定的范围内,则抛出异常,数字和字母的优先级最低
*
* @param c
* @return
* @throws Exception
*/
public static int getPriority(char c) throws Exception {
int priority = -1;
if (Character.isDigit(c)) {
priority = -1;
} else if (Character.isLetter(c)) {
priority = 0;
} else {
if (c == '(') {
priority = 8;
} else if (c == '*' || c == '/') {
priority = 5;
} else if (c == '+' || c == '-') {
priority = 4;
} else if (c == ')') {
priority = -2;
} else {
throw new Exception("无法解析的前序表达式: " + c);
}
}
return priority;
}
/**
* 计算栈结果
* 6+5*8
* @param s
* @return
*/
public static float calstack(String s) {
StackFloat stack = new StackFloat();
char[] c = s.toCharArray();
try {
for (int i = 0; i c.length; i++) {
int priority = getPriority(c[i]);
if (priority == -1) {
stack.push(new Float(Character.digit(c[i], 10)));
} else {
stack.push(cal(stack.pop(), stack.pop(), c[i]));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stack.pop();
}
/**
* a b 运算
* @param a
* @param b
* @param opertor
* @return
*/
public static float cal(float a, float b, char opertor) {
float r = 0;
switch (opertor) {
case '+':
r = a + b;
break;
case '-':
r = a - b;
break;
case '*':
r = a * b;
break;
case '/':
r = a / b;
break;
}
return r;
}
}
java :转变为逆波兰表示式的代码报错:堆栈溢出,怎么解决?
while(Character.isDigit(chars[i])||chars[i]=='.') {
s.append(chars[i]);
}
这一段是死循环。。stack一直追加参数,所以溢出了
怎样用JAVA写出逆波兰表达式求值部分的源代码(提供代码框架)
下面的代码是用来计算表达式的,看看是不是你要的
public class OPNode {
char op;// 运算符号
int level;// 优先级
//设置优先级
public OPNode(String op) {
this.op = op.charAt(0);
if (op.equals("+") || op.equals("-")) {
this.level = 1;
} else if (op.equals("*") || op.equals("/")) {
this.level = 2;
} else if (op.equals("(")) {
this.level = -3;
} else {
this.level = -1;
}
}
}
//主类
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OPText {
public static void main(String[] args) {
String expression = "2+2+(8-2)/3";// 要计算的表达式
List list = new LinkedList();
//正则式
Pattern entryOfExpression = Pattern
.compile("[0-9]+(\\.[0-9]+)?|\\(|\\)|\\+|-|\\*|/");
Deque stack = new LinkedList();//栈
Matcher m = entryOfExpression.matcher(expression);
while (m.find()) {
//提取语素
String nodeString = expression.substring(m.start(), m.end());
if (nodeString.matches("[0-9].*")) {
list.add(Double.valueOf(nodeString));//如果是数字直接送入列表
} else {
OPNode opn = new OPNode(nodeString);//如果是运算符
int peekLevel = (stack.peek() == null) ? 0 : ((OPNode) stack
.peek()).level;
if (opn.level =peekLevel) {
stack.push(opn);//新的运算符比旧的优先级别高则入栈
} else {
if (opn.level == -1) {
OPNode temp = (OPNode) stack.pop();
while (temp.level != -3) {//如果为"("则一直出栈一直到")"
list.add(temp);
System.out.println(nodeString);
temp = (OPNode) stack.pop();
}
} else if (opn.level == -3) {
stack.push(opn);
} else {//如果新运算符比栈顶运算符底则一直出栈
OPNode temp = (OPNode) stack.pop();
while (temp.level opn.level) {
list.add(temp);
if (stack.isEmpty()) {
break;
}
temp = (OPNode) stack.pop();
}
stack.push(opn);
}
}
}
}
OPNode temp = null;
while (!stack.isEmpty()) {
temp = (OPNode) stack.pop();
list.add(temp);
}//后续表达式计算
stack.clear();
for (Object o : list) {
if (o instanceof Double) {
stack.push(o);//为数字入栈
} else {
double op2 = ((Double) stack.pop()).doubleValue();
double op1 = ((Double) stack.pop()).doubleValue();
switch (((OPNode) o).op) {
case '+':
stack.push(op1 + op2);
break;
case '-':
stack.push(op1 - op2);
break;
case '*':
stack.push(op1 * op2);
break;
case '/':
stack.push(op1 / op2);
break;
}
}
}
System.out.println("结果为:" + stack.pop());
}
}
呃,太晚了,没心思去改了
明天再说
网站栏目:逆波兰java代码,逆波兰表达式java
本文URL:http://myzitong.com/article/hdhcjo.html