Created
August 21, 2013 13:07
-
-
Save loosechainsaw/6294238 to your computer and use it in GitHub Desktop.
Dijkstra Two Stack Solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stack> | |
#include <stdexcept> | |
#include <cctype> | |
#include <cstdlib> | |
using namespace std; | |
int evaluate(string const &expression){ | |
stack<char> operators; | |
stack<int> values; | |
int result = 0; | |
for(auto it = expression.begin(); it != expression.end(); ++it){ | |
if(*it == '(' || std::isspace(*it)) | |
{ | |
continue; | |
}else if( std::isdigit(*it)) | |
{ | |
char value = *it; | |
values.push(atoi(&value)); | |
}else if(*it == ')') | |
{ | |
int value1 = values.top(); | |
values.pop(); | |
int value2 = values.top(); | |
values.pop(); | |
int op = operators.top(); | |
operators.pop(); | |
if(op == '+'){ | |
values.push(value1 + value2); | |
}else if(op == '-'){ | |
values.push(value1 - value2); | |
}else if(op == '/'){ | |
values.push(value1 / value2); | |
}else if(op == '*'){ | |
values.push(value1 * value2); | |
} | |
}else if(*it == '+' || *it == '-' || *it == '*' || *it == '/') | |
{ | |
operators.push(*it); | |
}else | |
{ | |
throw exception(); | |
} | |
} | |
result = values.top(); | |
values.pop(); | |
return result; | |
} | |
int main() | |
{ | |
cout << "The value of the expression is: " << evaluate(" ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) ") << endl; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment