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

重拾编程之路--数据结构--前缀表示法求值

2016-01-11 20:00 225 查看
package com.lulu.leetcode;

import java.util.Stack;

/**
* 波兰表达式求值(前缀表达式)---与后缀表达式不同的是计算两个数的值时,用第一个栈顶元素操作第二个栈顶元素
* 思路:
* 遇到变量或数字直接入栈;
* 遇到操作符计算栈顶两个元素的值,结果入栈
* @author lulu
*
*/
public class C_evalPN{
public int evalRPN(String[] tokens) {
if (tokens == null)
return 0;
Stack<String> stack = new Stack<String>();
int result = 0;
for (int i = 0; i < tokens.length; i++) {
String ch = tokens[i];
int num1 = 0;
int num2 = 0;
switch (ch) {
case "+":
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
result =num2+num1;
stack.push(result+"");
break;
case "-":
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
result =num2-num1;
stack.push(result+"");
break;
case "*":
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
result = num2 * num1;
stack.push(result+"");
break;
case "/":
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
result = num2 / num1;
stack.push(result+"");
break;

default:
stack.push(ch);
break;
}
}
if(!stack.isEmpty()){
return Integer.parseInt(stack.pop());
}
return result;

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