Write your question here.
I am trying to write an algorithm using stacks that converts an infix expression into a postfix expression(ex (6 + 13) * 2 – (5 + 1)/3 -> 613 + 2*5 1 +3 / -
My current output looks like 613+251+3/*
Please help! Thank you
//
//
//
//
#include <iostream>
#include <stack>
#include <string>
usingnamespace std;
//Function to return precedence of operators
int prec(char c)
{
int temp = 0;
if(c == '+' || c == '-')
temp = 1;
elseif(c == '*' || c == '/')
temp = 2;
return temp;
}
bool isOperator(char input)
{
if(input == '+' || input == '-' || input == '*' || input == '/')
returntrue;
returnfalse;
}
// The main function to convert infix expression
//to postfix expression
void infixToPostfix(string s)
{
stack<char> st; //stack for operators
string ns; //converted string
for(int i = 0; i < s.length(); i++)
{
// If the scanned character is an operand, add it to output string.
if(isdigit(s[i]))
ns+=s[i];
// If the scanned character is an ‘(‘, push it to the stack.
elseif(s[i] == '(')
st.push('(');
//If an operator is scanned
elseif(isOperator(s[i])){
bool found = false;
do{
if(st.empty())
{
st.push(s[i]);
found = true;
}
elseif(st.top() == '(')
{
st.push(s[i]);
found = true;
}
elseif(prec(s[i]) >= prec(st.top())){
st.push(s[i]);
found = true;
}
else{
ns+=st.top();
st.pop();
}
}while(!found);
}
// If the scanned character is an ‘)’, pop and to output string from the stack
// until an ‘(‘ is encountered. Pop and discard '('
elseif(s[i] == ')'){
while(st.top() != '(' && !isdigit(s[i])){
ns += st.top();
st.pop();
}
if(st.top() == '('){
st.pop();
}
}
}
//Pop all the remaining elements from the stacl
while(!st.empty())
{
ns += st.top();
st.pop();
}
cout << ns << endl;
}
int main()
{
string exp = "(6 + 13) * 2 – (5 + 1)/3";
infixToPostfix(exp);
return 0;
}