Skip to content

Instantly share code, notes, and snippets.

@skshetry
Last active June 16, 2017 03:03
Show Gist options
  • Save skshetry/ece3637f542f778cfb558b52ee4ba4c4 to your computer and use it in GitHub Desktop.
Save skshetry/ece3637f542f778cfb558b52ee4ba4c4 to your computer and use it in GitHub Desktop.
Implementation of algorithm to convert infix expressions to postfix and prefix expressions.
#include "lib/stack.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cctype>
using std::string;
using std::cin;
using std::cout;
class ArithmeticExpression{
char operators[6] = {'/', '*', '+', '-', '^'};
Stack<char> operatorstack;
string expression;
int precedence(char ops){
int weight;
switch(ops){
case '(':
weight = 5;
break;
case '^':
weight = 4;
break;
case '/':
case '*':
weight = 3;
break;
case '+':
case '-':
weight = 2;
break;
default:
weight = 1;
break;
}
return weight;
}
public:
ArithmeticExpression(string expression):expression(expression){ }
string infixToPostfix(){
int index = 0;
string postfixexpr;
while(index <= expression.length()){
char token = expression[index];
if(token == ' ' || token == '\t') { }
else if(std::isalpha(token)){
postfixexpr += token;
}
else if(std::strchr(operators,token)!=NULL){
while(
!operatorstack.empty()
&& (precedence(token) <= precedence(operatorstack.top()))
&& operatorstack.top()!='('
) {
postfixexpr += operatorstack.top();
operatorstack.pop();
}
operatorstack.push(token);
}
else if(token == '('){
operatorstack.push(token);
}
else if(token == ')'){
while(!operatorstack.empty() && operatorstack.top()!='('){
postfixexpr += operatorstack.top();
operatorstack.pop();
}
operatorstack.pop();
}
index++;
}
while(!operatorstack.empty()){
postfixexpr += operatorstack.top();
operatorstack.pop();
}
return postfixexpr;
}
string infixToPrefix(){
std::reverse(expression.begin(), expression.end());
cout << expression << '\n';
for(char& c:expression){
if(c =='('){
c = ')';
}
else if( c== ')'){
c = '(';
}
}
cout << expression << '\n';
string prefixexpr = infixToPostfix();
cout << prefixexpr << '\n';
std::reverse(prefixexpr.begin(), prefixexpr.end());
cout << prefixexpr << '\n';
std::reverse(expression.begin(), expression.end());
for(char& c:expression){
if(c =='('){
c = ')';
}
else if( c== ')'){
c = '(';
}
}
return prefixexpr;
}
};
int main(int argc, char* argv[]){
string expression; //"a+(b*c-(d/e-f)*g)*h";
cout << "Enter expression: "; std::cin >> expression;
ArithmeticExpression abcd(expression);
cout << abcd.infixToPrefix();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment