Last active
April 15, 2022 15:40
-
-
Save dgodfrey206/2166768c4c2825521053 to your computer and use it in GitHub Desktop.
Using Dijkstra's two-stack algorithm to parse simple arithmetic expressions
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 <string> | |
#include <stack> | |
void calculate(std::stack<int>& numbers, std::stack<char>& operators); | |
int main() | |
{ | |
std::stack<int> numbers; | |
std::stack<char> operators; | |
for (char c; std::cin >> c; ) | |
{ | |
if (std::string("+-*/").find(c) != std::string::npos) | |
operators.push(c); | |
if (std::isdigit(c)) | |
numbers.push(c - '0'); | |
if (c == ')') | |
calculate(numbers, operators); | |
} | |
int result = numbers.top(); | |
std::cout << result; | |
} | |
template <class T> | |
T pop(std::stack<T>& s) | |
{ | |
T popped = s.top(); | |
s.pop(); | |
return popped; | |
} | |
void calculate(std::stack<int>& numbers, std::stack<char>& operators) | |
{ | |
int a = pop(numbers); | |
int b = pop(numbers); | |
char op = pop(operators); | |
switch (op) | |
{ | |
case '+': | |
numbers.push(a + b); | |
break; | |
case '-': | |
numbers.push(a - b); | |
break; | |
case '/': | |
numbers.push(a / b); | |
break; | |
case '*': | |
numbers.push(a * b); | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment