From 5cf6c985c4542da84203329e5521b46abd6cec61 Mon Sep 17 00:00:00 2001 From: kanan010506 Date: Sat, 11 Oct 2025 13:26:15 +0530 Subject: [PATCH] Infix to Postfix conversion --- CPP/Stacks_Queues/infixToPostfix.cpp | 55 ++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 CPP/Stacks_Queues/infixToPostfix.cpp diff --git a/CPP/Stacks_Queues/infixToPostfix.cpp b/CPP/Stacks_Queues/infixToPostfix.cpp new file mode 100644 index 0000000..2651a1e --- /dev/null +++ b/CPP/Stacks_Queues/infixToPostfix.cpp @@ -0,0 +1,55 @@ +//infix to postfix conversion +#include +#include +#include +using namespace std; + +int priority(char op) { + if (op == '^') return 3; + if (op == '*' || op == '/') return 2; + if (op == '+' || op == '-') return 1; + return 0; +} + +string infixToPostfix(string s){ + int n = s.size(); + int i=0; + stack st; + string ans = ""; + while(i='A' && s[i]<='Z') || (s[i]>='a' && s[i]<='z') || (s[i]>='0' && s[i]<='9')){ + ans = ans + s[i]; + } + else if(s[i] == '('){ + st.push(s[i]); + } + else if(s[i] == ')'){ + while(!st.empty() && st.top() != '('){ + ans += st.top(); + st.pop(); + } + st.pop(); // to pop opening bracket + } + else{//left only with operator + while(!st.empty() && (priority(s[i]) < priority(st.top()) || (priority(s[i]) == priority(st.top()) && s[i]!= '^'))){ + ans += st.top(); + st.pop(); + } + st.push(s[i]); + } + i++; + } + while(!st.empty()){ + ans += st.top(); + st.pop(); + } + return ans; +} + +int main(){ + string s = "A+B*(C^D-E)^F+G*H-I"; + string ans = infixToPostfix(s); + cout<