Task: Convert the given string from Infix to Postfix.
Example:
Input:
1
A*(B+C)/D
Output:
ABC+*D/
Here is the Code:
Program in C++:
- #include <iostream>
- #include <bits/stdc++.h>
- using namespace std;
- int prec(char c)
- {
- if(c=='^')
- {
- return 3;
- }
- else if(c=='*'||c=='/')
- {
- return 2;
- }
- else if(c=='+'||c=='-')
- {
- return 1;
- }
- else
- {
- return -1;
- }
- }
- int infixToPostfix(string s)
- {
- stack<char> st;
- for(int i=0;i<s.length();i++)
- {
- if(isalpha(s[i]))
- {
- cout<<s[i];
- }
- else if(s[i]==')')
- {
- while(st.top()!='(')
- {
- cout<<st.top();
- st.pop();
- }
- st.pop();
- }
- else
- {
- if(st.empty()==true)
- {
- st.push(s[i]);
- }
- else
- {
- if(s[i]=='('||st.top()=='('||prec(s[i])>prec(st.top()))
- {
- st.push(s[i]);
- }
- else
- {
- while(st.empty()==false&&prec(s[i])<=prec(st.top())&&st.top()!='(')
- {
- cout<<st.top();
- st.pop();
- }
- st.push(s[i]);
- }
- }
- }
- }
- while(st.empty()==false)
- {
- cout<<st.top();
- st.pop();
- }
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- string str;
- getline(cin, str);
- infixToPostfix(str);
- cout<<endl;
- }
- return 0;
- }
Here is the Video: