forked from fineanmol/Hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
we can convert postfix to infix expression
- Loading branch information
1 parent
039810f
commit b4e2832
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
Program's_Contributed_By_Contributors/C++ Programs/Stacks/postfix_to_infix.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |