File tree Expand file tree Collapse file tree 1 file changed +102
-0
lines changed
Expand file tree Collapse file tree 1 file changed +102
-0
lines changed Original file line number Diff line number Diff line change 1+ #include<bits/stdc++.h>
2+ using namespace std ;
3+ int priority(char c)
4+ {
5+ if(c=='*' || c=='/')
6+ return 1;
7+ else if(c=='+' || c=='-')
8+ return 2;
9+ }
10+ bool isOperator(char c)
11+ {
12+ if(c == '+' || c=='-' || c=='*' || c=='/')
13+ return true ;
14+ else
15+ return false ;
16+ }
17+ string Rem_superfluous(string s)
18+ {
19+ stack<string> st ;
20+ for(int i=0;i<s.size();i++)
21+ {
22+ if(!isOperator(s[i])){
23+ string x(1,s[i]) ;
24+ st.push(x) ;
25+ }
26+ else
27+ {
28+ string s2 = st.top() ;
29+ st.pop() ;
30+ string s1 = st.top() ;
31+ st.pop() ;
32+ string x ;
33+ string ch(1,s[i]) ;
34+ if(priority(s[i])==1 || i==s.size()-1)
35+ x = s1+ch+s2;
36+ else if(priority(s[i])==2)
37+ x = "("+s1+ch+s2+")";
38+ st.push(x) ;
39+ }
40+ }
41+ if(st.size() == 1){
42+ return st.top() ;
43+ }
44+ }
45+ string infix_to_postfix(string s)
46+ {
47+ s = "("+s+")" ;
48+ stack<char> st ;
49+ string ans = "" ;
50+ for(int i=0;i<s.size();i++)
51+ {
52+ if(s[i] == '(')
53+ st.push(s[i]) ;
54+ else if(!isOperator(s[i]) && s[i] != ')')
55+ {
56+ string x(1,s[i]);
57+ ans+=x;
58+ }
59+ else if(isOperator(s[i]))
60+ {
61+ char x = st.top() ;
62+ if(isOperator(x))
63+ {
64+ if(priority(x)<priority(s[i]))
65+ {
66+ string ch(1,x);
67+ ans+=ch ;
68+ st.pop() ;
69+ st.push(s[i]);
70+ }
71+ else
72+ {
73+ st.push(s[i]);
74+ }
75+ }
76+ else
77+ st.push(s[i]);
78+ }
79+ else if(s[i] == ')')
80+ {
81+ while(st.top() != '(')
82+ {
83+ char x = st.top() ;
84+ string ch(1,x) ;
85+ ans+=ch ;
86+ st.pop() ;
87+ }
88+ st.pop() ;
89+ }
90+ }
91+
92+ return ans ;
93+ }
94+ int main()
95+ {
96+ string s1 ;
97+ cout<<"Enter the Postfix Expression : ";
98+ cin>>s1 ;
99+ string ans = Rem_superfluous(infix_to_postfix(s1)) ;
100+ cout<<endl<<"Output :- "<<ans<<endl ;
101+ return 0 ;
102+ }
You can’t perform that action at this time.
0 commit comments