MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / postfix_eval

Function postfix_eval

code/chapter03/postfix_eval.rs:28–48  ·  view source on GitHub ↗
(postfix: &str)

Source from the content-addressed store, hash-verified

26}
27
28fn postfix_eval(postfix: &str) -> Option<i32> {
29 // 少于五个字符,不是有效的后缀表达式,因为表达式
30 // 至少两个操作数加一个操作符,还需要两个空格隔开
31 if postfix.len() < 5 { return None; }
32
33 let mut op_stack = Stack::new(); // 操作数栈
34 for token in postfix.split_whitespace() {
35 if "0" <= token && token <= "9" {
36 op_stack.push(token.parse::<i32>().unwrap());
37 } else {
38 // 对于减法和除法,顺序有要求
39 // 所以先出栈的是第二个操作数
40 let op2 = op_stack.pop().unwrap();
41 let op1 = op_stack.pop().unwrap();
42 let res = do_calc(token, op1, op2);
43 op_stack.push(res);
44 }
45 }
46
47 Some(op_stack.pop().unwrap())
48}
49
50// 执行数学运算
51fn do_calc(op: &str, op1: i32, op2: i32) -> i32 {

Callers 1

mainFunction · 0.70

Calls 4

do_calcFunction · 0.70
lenMethod · 0.45
pushMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected