If you have the
following expression:
(( A * (B + D)/E) - F * (G + H / K)))
Write C++ Program to convert infix
to postfix expression using the Stack Data Structure
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int prec(char c) {
switch(c){
case '^': return 3;
case '/':;
case '*':return 2;
case '+':;
case '-': return 1;
default: return -1;
}
}
void convertToPostfix(string s) {
stack<char> st;
string result;
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'))
result += c;
else if(c == '(')
st.push('(');
else if(c == ')') {
if(!st.empty()){
while(st.top() != '(')
{
result += st.top();
st.pop();
}
st.pop();
}
}
else {
while(!st.empty() && prec(s[i]) <= prec(st.top())) {
result += st.top();
st.pop();
}
st.push(c);
}
}
while(!st.empty()) {
result += st.top();
st.pop();
}
cout << result << endl;
}
int main() {
string expr = "((A*(B+D)/E)-F*(G+H/K)))";
convertToPostfix(expr);
return 0;
}
Comments
Leave a comment