Created
September 29, 2022 08:57
-
-
Save Vaib215/a731cbf4025f9fb431eeb04a43a5fad1 to your computer and use it in GitHub Desktop.
Code that converts infix into postfix
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
#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