堆栈可能会对您有所帮助,请考虑:1 + (2 + 3)
创建两个堆栈,一个是数字,另一个是运算符。
当你找到一个数字时,放入数字堆栈,当你找到一个运算符时,放入运算符堆栈,当你找到“(”时什么都不做,当你找到一个“)”时,得到一个堆栈的两个数字和一个运算符,计算这两个数字并再次放入数字堆栈中,请参见代码循环:
//1 + (2 + 3)
operators = []
numbers = []
//I put the number in the numbers stack
//+ (2 + 3)
operators = []
numbers = [1]
--
// I put the operator in the operators stack
// (2 + 3)
operators = [+]
numbers = [1]
--
// 2 + 3)
//find a "(" char, do nothing
operators = [+]
numbers = [1]
--
// + 3)
operators = [+]
numbers = [1, 2]
--
// 3)
operators = [+, +]
numbers = [1, 2]
--
// )
operators = [+, +]
numbers = [1, 2, 3]
--
//found a ")", get two items of stack of numbers (3,2), and one item of operators stack (+), result is 5, put back in the stack of numbers
operators = [+]
numbers = [1, 5]
--
//When finished string, get two elements and one operator until finish the stack
// get two elements of numbers stack (1,5) and one of operators stack +, result is 6
希望对你有帮助