Skip to content

Commit

Permalink
Create postfix_to_infix.cpp
Browse files Browse the repository at this point in the history
we can convert postfix to infix expression
  • Loading branch information
pranavupadhyay123 committed Oct 6, 2023
1 parent 039810f commit b4e2832
Showing 1 changed file with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <iostream>
#include <stack>
#include <string>

using namespace std;

bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}

string postfixToInfix(string postfix) {
stack<string> st;

for (char c : postfix) {
if (!isOperator(c)) {
st.push(string(1, c));
} else {
string operand2 = st.top();
st.pop();
string operand1 = st.top();
st.pop();

string newExpr = "(" + operand1 + " " + c + " " + operand2 + ")";
st.push(newExpr);
}
}

return st.top();
}

int main() {
string postfixExpression;
cout << "Enter a postfix expression: ";
cin >> postfixExpression;

string infixExpression = postfixToInfix(postfixExpression);

cout << "Infix expression: " << infixExpression << endl;

return 0;
}

0 comments on commit b4e2832

Please sign in to comment.