用Java實現的一個逆波蘭表達式計算的小demo
public class NiBoLan {
/**
* @param args
*/
public static void main(String[] args) {
// String str = "1 + ( 2 - 3 ) * 4 + 10 / 5";
String str = "2 * 3 + 6 / 2 * ( 3 - 2 ) + 4";
String[] strings = str.split(" ");
String[] result = middleToLast(strings);
int aa = calculate(result);
System.out.println(aa);
}
/**
* 將后綴表達式通過棧結構計算出最終結果
* @param strings
* @return
*/
private static int calculate(String[] strings){
Stack<Integer> stack = new Stack<Integer>(strings.length);
for (int i = 0; i < strings.length; i++) {
String str = strings[i];
if(str != null){
if("+".equals(str)){
int a = stack.pop();
int b = stack.pop();
stack.push(b + a);
}else if("-".equals(str)){
int a = stack.pop();
int b = stack.pop();
stack.push(b - a);
}else if("*".equals(str)){
int a = stack.pop();
int b = stack.pop();
stack.push(b * a);
}else if("/".equals(str)){
int a = stack.pop();
int b = stack.pop();
stack.push(b / a);
}else{
// 是數字,直接入棧
stack.push(Integer.parseInt(str));
}
}
}
return stack.pop();
}
/**
* 通過棧結構將中綴表達式轉換成后綴表達式
* @param strings
* @return
*/
private static String[] middleToLast(String[] strings) {
Stack<String> stack = new Stack<String>(strings.length);
String [] result = new String[strings.length];
int resultCount = 0;
for (int i = 0; i < strings.length; i++) {
String str = strings[i];
// 遍歷過程中如果要加入棧頂的符號是+或者-,如果棧為空,則直接添加,如果不為空,因為+ 和 -比+ - * / 的優先級都小。所以
// 將當前棧頂符號pop出棧放入到結果中,繼續判斷當前棧頂是否為空,繼續彈棧,直到棧為null為止
if("+".equals(str) || "-".equals(str)){
if(!stack.isEmpty()){
while("+".equals(stack.peek())
|| "-".equals(stack.peek())
||"*".equals(stack.peek())
||"/".equals(stack.peek())){
String pop = stack.pop();
result[resultCount++] = pop;
}
}
stack.push(str);
}else if("*".equals(str) || "/".equals(str)){
// 遍歷過程中如果要加入棧頂的符號是*或者/ 判斷當前棧頂符號是否也為* /, 如果為* /,就要彈棧加入結果集,并繼續判斷
while("*".equals(stack.peek())||"/".equals(stack.peek())){
String pop = stack.pop();
result[resultCount++] = pop;
}
stack.push(str);
}else if("(".equals(str)){
// 左括號直接入棧
stack.push(str);
}else if(")".equals(str)){
// 將到上一個左括號的符號彈棧加入結果集
while(!"(".equals(stack.peek())){
result[resultCount++] = stack.pop();
}
stack.pop();
}else{
// 是數字,直接加入結果集
result[resultCount++] = str;
}
}
// 遍歷完畢,沒有元素需要判斷了,將棧中元素依次彈出放入結果集中
while(!stack.isEmpty()){
result[resultCount++] = stack.pop();
}
return result;
}
/**
* 自定義棧結構
* @author youtl
*
* @param <T>
*/
static class Stack<T>{
private Object [] data;
private int top = -1;
public Stack(int length){
data = new Object[length];
}
public T push(T t){
addElement(t);
return t;
}
public T pop(){
if(top < 0){
return null;
}
T t = (T) data[top];
data[top] = null;
top--;
return t;
}
public T peek(){
if(top < 0){
return null;
}
return (T) data[top];
}
private void addElement(T t) {
data[++top] = t;
}
public int getLength(){
return (top+1);
}
public boolean isEmpty(){
return (top+1) > 0 ? false : true;
}
public void printStack(){
while(!isEmpty()){
System.out.println(pop());
}
}
}
}