美文网首页
利用栈解决逆波兰表达式问题

利用栈解决逆波兰表达式问题

作者: 梁森的简书 | 来源:发表于2021-02-04 23:47 被阅读0次
0.逆波兰表达式.png
0.逆波兰表达式流程.png
/// 利用栈解决逆波兰表达式问题
    private func testReversePolishNotation(){
        var stack = Stack()
        // 1+(1*2)-(2/1)=1
        let strArray = ["1", "1", "2", "*", "+", "2", "1", "/", "-"]
        for i in 0..<strArray.count {
            let str = strArray[i]
            switch str {
            case "+":
                let o1 = stack.pop() as! Int
                let o2 = stack.pop() as! Int
                let result = o2 + o1
                stack.push(item: result)
            case "-":
                let o1 = stack.pop() as! Int
                let o2 = stack.pop() as! Int
                let result = o2 - o1
                stack.push(item: result)
            case "*":
                let o1 = stack.pop() as! Int
                let o2 = stack.pop() as! Int
                let result = o2 * o1
                stack.push(item: result)
            case "/":
                let o1 = stack.pop() as! Int
                let o2 = stack.pop() as! Int
                let result = o2 / o1
                stack.push(item: result)
            default:
                let result = Int(str)!
                stack.push(item: result)
            }
        }
        let result = stack.pop() as! Int
        print("\(result)")
    }

demo地址:https://github.com/yangguanghei/studyDateStructure

相关文章

网友评论

      本文标题:利用栈解决逆波兰表达式问题

      本文链接:https://www.haomeiwen.com/subject/suaitltx.html