-
Notifications
You must be signed in to change notification settings - Fork 1
/
Multiple_parenthesis_matching.c
119 lines (119 loc) · 2.18 KB
/
Multiple_parenthesis_matching.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack
{
int size;
int top;
char *A;
};
void create(struct stack *s, char A[])
{
(*(s)).size = strlen(A);
(*(s)).top = (-1);
(*(s)).A = (char *)malloc((*(s)).size * sizeof(char));
}
void push(struct stack *s, char c)
{
if ((*(s)).top == (*(s)).size - 1)
{
printf("Stack Overflow!\n");
}
else
{
(*(s)).top++;
(*(s)).A[(*(s)).top] = c;
}
}
char pop(struct stack *s)
{
char c = '*';
if ((*(s)).top == (-1))
{
return c;
}
else
{
c = (*(s)).A[(*(s)).top];
(*(s)).top--;
return c;
}
}
int isempty(struct stack *s)
{
if ((*(s)).top == (-1))
{
return 1;
}
else
{
return 0;
}
}
int match(char a, char b)
{
if (a == '(' && b == ')')
{
return 1;
}
else if (a == '{' && b == '}')
{
return 1;
}
else if (a == '[' && b == ']')
{
return 1;
}
else
{
return 0;
}
}
int parenthesis_matcher(struct stack *s, char A[])
{
char popped;
for (int i = 0; A[i] != '\0'; i++)
{
if (A[i] == '(' || A[i] == '{' || A[i] == '[')
{
push(s, A[i]);
}
if (A[i] == ')' || A[i] == '}' || A[i] == ']')
{
popped = pop(s);
if (match(popped, A[i]) == 0)
{
return 0;
}
}
}
if (isempty(s) == 1)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
printf("Enter any expression:\n");
char A[100];
gets(A);
printf("\nEntered expression is:\n");
puts(A);
struct stack s;
create(&s, A);
if (parenthesis_matcher(&s, A) == 1)
{
printf("\nBALANCED\n");
}
else
{
printf("\nNOT BALANCED\n");
}
}
/*Parenthesis Matching doesn't mean that only frequency of opening bracket (of any type)
must be equal to its closing counterpart but
lastly opened bracket must be firstly closed by its closing counterpart.*/