-
Notifications
You must be signed in to change notification settings - Fork 2
/
BalancedBrackets.c
92 lines (74 loc) · 1.67 KB
/
BalancedBrackets.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <stdlib.h>
#define bool int
struct sNode{
char data;
struct sNode* next;
};
void push(struct sNode** top, int data);
int pop(struct sNode**top);
bool isMatch(char ch1, char ch2){
if((ch1=='('&&ch2==')')||(ch1=='['&&ch2==']')||(ch1=='{'&&ch2=='}'))
return 1;
else return 0;
}
bool isBalanced(char s[])
{
int i =0;
struct sNode * stack = NULL;
while(s[i])
{
if(s[i]=='('||s[i]=='{'||s[i]=='[')
push(&stack, s[i]);
if(s[i]==')' || s[i]=='}'|| s[i]==']')
{
if(stack==NULL)
return 0;
else if(!isMatch(pop(&stack),s[i]))
return 0;
}
i++;
}
if(stack==NULL) return 1;
else return 0;
}
int main(){
char s[100];
printf("Enter a bracket sequence: \n");
scanf("%[^\n]", &s);
if(isBalanced(s))
printf("Expression is Balanced.");
else
printf("Expression is not balanced.");
return 0;
}
void push( struct sNode** top, int data)
{
struct sNode* newnode = (struct sNode*)malloc(sizeof(struct sNode));
if(newnode == NULL){
printf("Newnode in push function is null\n");
getchar();
exit(0);
}
newnode->data = data;
newnode->next = (*top);
(*top) = newnode;
}
int pop(struct sNode** top_ref)
{
char res;
struct sNode * top;
if(*top_ref == NULL)
{
printf("Top is null\n");
getchar();
exit(0);
}
else{
top= *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}