Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dijkstra double stack #3

Open
barretlee opened this issue May 24, 2016 · 1 comment
Open

Dijkstra double stack #3

barretlee opened this issue May 24, 2016 · 1 comment

Comments

@barretlee
Copy link
Owner

barretlee commented May 24, 2016

/chapters/chapter-1-fundamentals/1.3-bags-queues-ans-stacks/evaluate.js

双栈算法表达式求值算法,例如 ( 1 + ( ( 2 + 3 ) * ( 4 + 5 ) )

@barretlee
Copy link
Owner Author

下面是算法。

function evaluate(input) {
  input = input.reverse();
  var len = input.length;
  var optStack = [];
  var valStack = [];
  while(len--) {
    var item = input[len];
    switch(item) {
      case "+":
      case "-":
      case "*":
      case "/":
        optStack.push(item);
        break;
      case "(":
        break;
      case ")":
        var a = valStack.pop();
        var b = valStack.pop();
        var opt = optStack.pop();
        valStack.push(eval(a + opt + b));
        break;
      default:
        valStack.push(item);
    }
  }
  return valStack.pop();
}

临时给自己的一个思考题:( + 1 ( * ( + 2 3 ) ( + 4 5 ) ),这个问题如何处理?

barretlee pushed a commit that referenced this issue Aug 26, 2016
Merge pull request #18 from StevenYuysy/master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant