Skip to content

Commit 261dfa6

Browse files
Merge pull request #536 from veerraj/master
Algorithm for balancing the parenthesis using c++
2 parents 8cd1b3d + db4e3c0 commit 261dfa6

File tree

1 file changed

+117
-0
lines changed

1 file changed

+117
-0
lines changed

C++/Balance_Paranthesis_Algorithm.cpp

+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
#define SIZE 5
4+
#include<iostream>
5+
using namespace std;
6+
char a[SIZE];
7+
int top=-1;
8+
void push(int data)
9+
{
10+
if(top==SIZE-1)
11+
{
12+
throw "Sorry! stack is full no more space\n";
13+
}
14+
else{
15+
a[++top]=data;
16+
// printf("element inserted\n");
17+
}
18+
}
19+
void pop()
20+
{
21+
22+
if(top==-1)
23+
{
24+
throw "empty stack can't be deleted\n";
25+
// printf("empty stack can't deleted\n");
26+
}
27+
else
28+
{
29+
//printf("deleted = %d\n",a[top]);
30+
top--;
31+
}
32+
33+
}
34+
int topIndex()
35+
{
36+
if(top==-1)
37+
{
38+
throw "Empty Stack";
39+
}
40+
else
41+
{
42+
return a[top];
43+
}
44+
}
45+
int size()
46+
{
47+
return top+1;
48+
}
49+
bool empty()
50+
{
51+
return top==-1;
52+
}
53+
int main()
54+
{
55+
/*char ele;
56+
char ch ='y';
57+
while(ch=='y')
58+
{
59+
60+
try{
61+
if(ele=='{')
62+
push(ele);
63+
else
64+
pop();
65+
cout<<"enter more put y";
66+
cin>>ch;
67+
}
68+
catch(const char *msg)
69+
{
70+
cout<<"not balanced";
71+
}
72+
}
73+
if(top==-1)
74+
cout<<"balanced";*/
75+
string braces="{[]}}";
76+
try{
77+
for(char c:braces)
78+
{
79+
if(c=='{' || c=='(' || c=='[')
80+
{
81+
push(c);
82+
}
83+
else{
84+
if(c=='}' && topIndex()=='{')
85+
{
86+
pop();
87+
}
88+
else if(c==')' && topIndex()=='(')
89+
{
90+
pop();
91+
}
92+
else if(c==']' && topIndex()=='[')
93+
{
94+
95+
pop();
96+
}
97+
else
98+
{
99+
throw "not balnced";
100+
}
101+
}
102+
}
103+
if(empty()==true)
104+
{
105+
cout<<"balanced";
106+
}
107+
else
108+
{
109+
cout<<"not balanced";
110+
}
111+
}
112+
catch(...)
113+
{
114+
cout<<"not balanced";
115+
}
116+
}
117+

0 commit comments

Comments
 (0)