Convert the expression into postfix notation and then verify if it is correct or not,direct answers for both 5conversion are not allowed for verification take dummy values for eachvariable.
a+b*(c/d-e)%(f+g*h)-i
#include<bits/stdc++.h>
using namespace std;
int prec(char a) {
if(a == '^')
return 3;
else if(a == '/' || a=='*')
return 2;
else if(a == '+' || a == '-')
return 1;
else
return -1;
}
void infix_to_postfix(string s) {
stack<char> stk;
string res;
for(int i = 0; i < s.length(); i++) {
char c = s[i];
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
res += c;
else if(c == '(')
stk.push('(');
else if(c == ')') {
while(stk.top() != '(')
{
res += stk.top();
stk.pop();
}
stk.pop();
}
else {
while(!stk.empty() && prec(s[i]) <= prec(stk.top())) {
res += stk.top();
stk.pop();
}
stk.push(c);
}
}
while(!stk.empty()) {
res += stk.top();
stk.pop();
}
cout << res << endl;
}
int main() {
string expression = "a+b*(c/d-e)%(f+g*h)-i";
infix_to_postfix(expression);
return 0;
}
Comments
Leave a comment