Skip to content

Instantly share code, notes, and snippets.

@Vaib215
Created September 29, 2022 08:57
Show Gist options
  • Save Vaib215/a731cbf4025f9fb431eeb04a43a5fad1 to your computer and use it in GitHub Desktop.
Save Vaib215/a731cbf4025f9fb431eeb04a43a5fad1 to your computer and use it in GitHub Desktop.
Code that converts infix into postfix
#include <bits/stdc++.h>
using namespace std;
int precedence(char k){
if(k == '^') return 3;
else if(k == '/' || k =='*') return 2;
else if(k == '+' || k == '-') return 1;
else return -1;
}
int main() {
stack<char> st;
string s;
cin>>s;
for(auto i:s){
if((i>='a' && i<='z')||(i>='A' && i<='Z')||(i>='0' && i<='9')){
cout<<i;
}
else if(i=='(') st.push(i);
else if(i==')'){
while(st.top()!='('){
cout<<st.top();
st.pop();
}
st.pop();
}
else{
while(!st.empty()&& precedence(i)<=precedence(st.top())){
cout<<st.top();
st.pop();
}
st.push(i);
}
}
while(!st.empty()){
cout<<st.top();
st.pop();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment