20155306 第十一周课堂作业——栈的应用
20155306 第十一周课堂作业——栈的应用
一、表达式的后缀表达式
求出如下图的后缀表达式:
答案为: ab * cde / - f * +
二、Java实现后缀表达式求值
-需补充的源代码:
import java.util.StringTokenizer;
import java.util.Stack;
public class MyDC {
/**
* constant for addition symbol
*/
private final char ADD = '+';
/**
* constant for subtraction symbol
*/
private final char SUBTRACT = '-';
/**
* constant for multiplication symbol
*/
private final char MULTIPLY = '*';
/**
* constant for division symbol
*/
private final char DIVIDE = '/';
/**
* the stack
*/
private Stack<Integer> stack;
public MyDC() {
stack = new Stack<Integer>();
}
public int evaluate(String expr) {
int op1, op2, result = 0;
String token;
StringTokenizer tokenizer = new StringTokenizer(expr);
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
//如果是运算符,调用isOperator
if (isOperator(token)) {
//从栈中弹出操作数2
//从栈中弹出操作数1
//根据运算符和两个操作数调用evalSingleOp计算result;
//计算result入栈;
} else//如果是操作数
//操作数入栈;
}
return result;
}
private boolean isOperator(String token) {
return (token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/"));
}
private int evalSingleOp(char operation, int op1, int op2) {
int result = 0;
switch (operation) {
case ADD:
result = op1 + op2;
break;
case SUBTRACT:
result = op1 - op2;
break;
case MULTIPLY:
result = op1 * op2;
break;
case DIVIDE:
result = op1 / op2;
}
return result;
}
}
- 测试代码:
import java.util.Scanner;
public class MyDCTest {
public static void main(String[] args) {
String expression, again;
int result;
try {
Scanner in = new Scanner(System.in);
do {
MyDC evaluator = new MyDC();
System.out.println("Enter a valid postfix expression: ");
expression = in.nextLine();
result = evaluator.evaluate(expression);
System.out.println();
System.out.println("That expression equals " + result);
System.out.print("Evaluate another expression [Y/N]? ");
again = in.nextLine();
System.out.println();
}
while (again.equalsIgnoreCase("y"));
} catch (Exception IOException) {
System.out.println("Input exception reported");
}
}
}
- 添加的代码及具体解释:
if语句是用于判断是否为运算符:若输入为运算符,则if语句为真,则弹出紧靠它的两个操作数进行运算:
if (isOperator(token)) {
从栈中弹出操作数2和操作数一:
op2 = (stack.pop()).intValue();//从栈中弹出操作数2
op1 = (stack.pop()).intValue();//从栈中弹出操作数1
提取操作符+、-、*、/:
char operation = token.charAt(0);
调用函数evalSingleOp进行运算,把结果赋给result:
result =evalSingleOp(operation, op1, op2);
把计算结果result压入栈中:
stack.push(new Integer(result));
如果是操作数,则把操作数压入栈,下次计算的时候还需要利用上次的计算结果进行计算:
else
stack.push(new Integer(Integer.parseInt(token)));
- 因此,完整的插入程序为:
if (isOperator(token)) {//if语句是用于判断是否为运算符:若输入为运算符,则if语句为真,则弹出紧靠它的两个操作数进行运算
op2 = (stack.pop()).intValue();//从栈中弹出操作数2
op1 = (stack.pop()).intValue();//从栈中弹出操作数1
char operation = token.charAt(0);// 提取操作符+、-、*、/
result =evalSingleOp(operation, op1, op2);//调用函数进行运算,把结果赋给result
stack.push(new Integer(result)); // 把计算结果result压入栈中,下次计算的时候还需要利用上次的计算结果进行计算。
} else//如果是操作数
stack.push(new Integer(Integer.parseInt(token)));//把操作数压入栈;
- 运行结果截图:
本代码链接:码云链接——栈的应用