Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active April 15, 2022 15:40
Show Gist options
  • Save dgodfrey206/2166768c4c2825521053 to your computer and use it in GitHub Desktop.
Save dgodfrey206/2166768c4c2825521053 to your computer and use it in GitHub Desktop.
Using Dijkstra's two-stack algorithm to parse simple arithmetic expressions
#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