标签:class color getline [] stdout 表达 lin pre 用两个
//用两个stack来计算表达式的值
java版本:
import edu.princeton.cs.algs4.*; public class Evaluate { public static void main(String[] args) { Stack<String> ops = new Stack<String>(); Stack<Double> vals = new Stack<Double>(); while(!StdIn.isEmpty())// linux下终止输入(CTRL + d) { String s = StdIn.readString(); if(s.equals("(")); else if(s.equals("+")) ops.push(s); else if(s.equals("-")) ops.push(s); else if(s.equals("*")) ops.push(s); else if(s.equals("/")) ops.push(s); else if(s.equals("sqrt")) ops.push(s); else if(s.equals(")")) { String op = ops.pop(); double v = vals.pop(); if(op.equals("+")) v = vals.pop() + v; else if(op.equals("-")) v = vals.pop() - v; else if(op.equals("*")) v = vals.pop() * v; else if(op.equals("/")) v = vals.pop() / v; else if(op.equals("sqrt")) v = Math.sqrt(v); vals.push(v); } else vals.push(Double.parseDouble(s)); } StdOut.println(vals.pop()); } }
c++版本:
#include <iostream> #include <stack> #include <string> int main() { using namespace std; stack<double> s1; stack<char> s2; string str; cout << "input a expression: " << endl; getline(cin,str); char ch; char ch2; int i = 0; while(i < str.length()) { ch = str[i]; if(ch == ‘(‘); else if(ch == ‘+‘) s2.push(ch); else if(ch == ‘-‘) s2.push(ch); else if(ch == ‘*‘) s2.push(ch); else if(ch == ‘/‘) s2.push(ch); else if(ch == ‘)‘) { ch2 = s2.top(); s2.pop(); double v = s1.top(); s1.pop(); if(ch2 == ‘+‘) { v = s1.top() + v; s1.pop(); } else if(ch2 == ‘-‘) { v = s1.top() - v; s1.pop(); } else if(ch2 == ‘*‘) { v = s1.top() * v; s1.pop(); } else if(ch2 == ‘/‘) { v = s1.top() / v; s1.pop(); } s1.push(v); } else if(ch == ‘ ‘); else s1.push(ch - ‘0‘); i++; } cout << " the answer is " << s1.top() << endl; return 0; }
Dijkstra‘s Two-Stack Algorithm for Expression Evalution
标签:class color getline [] stdout 表达 lin pre 用两个
原文地址:https://www.cnblogs.com/w-j-c/p/8973216.html