Check Balanced Parentheses in C++
Check Balanced Parentheses in C++
Declare the stack S. Now traverse the expression and look or open parentheses D!rin" traversin"# i the character o!nd is a startin" $racket i.e. %&%& or &'& or &()*# then p!sh it to stack. I the character o!nd is a closin" $racket %)*) or )+) or ),&* then pop ro- stack and i the popped character is the -atchin" startin" $racket then it is a $alanced expression else parenthesis are not $alanced. A ter the traversal# i the stack is still not e-pt. i.e. it contains startin" $rackets then it is not $alanced.
/0 0 122 3ro"ra- to 1heck or $alanced paranthesis $. !sin" Stacks 0/ 4incl!de 5iostrea-6 4incl!de 5cstrin"6 4incl!de 5strin".h6
!sin" na-espace std7 //stack str!ct node ' char data7 node 0next7 +0p 8 N9LL# 0top 8 N9LL# 0save 8 N9LL#0ptr7 void p!sh%char x* //p!sh operation ' p 8 new node7 p:6data 8 x7 p:6next 8 N9LL7
i %top 88 N9LL* ' top 8 p7 + else ' save 8 top7 top 8 p7 p:6next 8 save7 + + char pop%* //pop operation ' i %top 88 N9LL* ' co!t55;!nder low<<;7 + else ' ptr 8 top7 top 8 top:6next7 ret!rn%ptr:6data*7 delete ptr7 + + int -ain%*
' int i7 !sin" std==strlen7 char c(>?,# a# .# @7 co!t55;enter the expression=An;7 cin66c7 or%i 8 ?7 i5strlen%c*7 i22* ' i %%c(i, 88 )%)* BB %c(i, 88 )')* BB %c(i, 88 )()** ' p!sh%c(i,*7 + else ' switch%c(i,* ' case )*)= a 8 pop%*7 i %%a 88 )')* BB %a 88 )()** ' co!t55;invalid expr<<;7 // "etch%*7 + $reak7 case )+)= . 8 pop%*7 i %%. 88 )()* BB %. 88 )%)**
' co!t55;invalid expr<<;7 // "etch%*7 + $reak7 case ),)= @ 8 pop%*7 i %%@ 88 )')* BB %@ 88 )%)** ' co!t55;invalid expr<<;7 // "etch%*7 + $reak7 + + + i %top 88 N9LL* ' co!t55;$alanced expr<<;7 + else ' co!t55;not $alanced;7 + // "etch%*7 +