File tree Expand file tree Collapse file tree 1 file changed +89
-0
lines changed Expand file tree Collapse file tree 1 file changed +89
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include<stdio.h>
2
+ #include<stdlib.h>
3
+ #include<string.h>
4
+ #define size 100
5
+
6
+ struct node
7
+ {
8
+ char data;
9
+ struct node* link;
10
+ };
11
+ int c=0; // c used as counter to check if stack is empty or not
12
+ struct node * head; //declaring head pointer globally assigned to NULL
13
+
14
+ void push(char x) //function for pushing
15
+ {
16
+ struct node *p,*temp;
17
+ temp=(struct node*)malloc(sizeof(struct node));
18
+ temp->data=x;
19
+ if(head==NULL) //will be execute only one time i.e, 1st time push is called
20
+ {
21
+ head=temp;
22
+ p=head;
23
+ p->link=NULL;
24
+ c++;
25
+ }
26
+ else
27
+ {
28
+ temp->link=p;
29
+ p=temp;
30
+ head=p;
31
+ c++;
32
+ }
33
+
34
+ }
35
+ char pop(void) //function for pop
36
+ {
37
+ char x;
38
+ struct node*p=head;
39
+ x=p->data;
40
+ head=p->link;
41
+ free(p);
42
+ c--;
43
+ return x;
44
+
45
+ }
46
+
47
+ int isBalanced(char *s) {
48
+ int i=0;char x;
49
+ while(s[i]!='\0') //loop for covering entire string of brackets
50
+ {
51
+ if(s[i]=='{'||s[i]=='('||s[i]=='[') //if opening bracket then push
52
+ push(s[i]);
53
+ else
54
+ {
55
+ if(c<=0) //i.e, stack is empty as only opening brackets are added to stack
56
+ return 0;
57
+
58
+
59
+ x=pop();
60
+ if( x=='{'&&s[i]!='}')
61
+ return 0;
62
+ if(x=='['&&s[i]!=']')
63
+ return 0;
64
+ if(x=='('&&s[i]!=')')
65
+ return 0 ;
66
+ }i++;
67
+ }
68
+ if(c==0) //at end if stack is empy which means whole process has been performed correctly so retuen 1
69
+ return 1;
70
+ else
71
+ return 0;
72
+ }
73
+
74
+ int main() {
75
+ int t;
76
+ scanf("%d",&t);
77
+ for(int a0 = 0; a0 < t; a0++){
78
+ char s[size];
79
+ int result;
80
+ scanf("%s",s);
81
+ result = isBalanced(s);
82
+ if(result==1)
83
+ printf("\nYES");
84
+ else
85
+ printf("\nNO");
86
+
87
+ }
88
+ return 0;
89
+ }
You can’t perform that action at this time.
0 commit comments