Skip to content

Commit a0e6d90

Browse files
Merge pull request #202 from Hitanshu123/master
Remove Superfluous Brackets in Expression
2 parents 0bd6990 + ea1622d commit a0e6d90

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

Remove Superfluous Brackets.txt

+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
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+
}

0 commit comments

Comments
 (0)