-
Notifications
You must be signed in to change notification settings - Fork 1
/
Parenthesis_matching_using_stack.c
102 lines (102 loc) · 1.91 KB
/
Parenthesis_matching_using_stack.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
#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)).A = (char *)malloc((*(s)).size * sizeof(char));
(*(s)).top = (-1);
}
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;
}
}
int pop(struct stack *s)
{
char x = '*';
if ((*(s)).top == (-1))
{
return x;
}
else
{
x = (*(s)).A[(*(s)).top];
(*(s)).top--;
return x;
}
}
int isempty(struct stack *s)
{
if ((*(s)).top == (-1))
{
return 1;
}
else
{
return 0;
}
}
int parenthesis_matcher(struct stack *s, char A[]) // character array=string
{
for (int i = 0; A[i] != '\0'; i++)
{
if (A[i] == '(')
{
push(s, A[i]);
}
else if (A[i] == ')')
{
if (isempty(s) == 1)
{
return 0;
}
else
{
pop(s);
}
}
}
if (isempty(s) == 1)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
struct stack o;
char A[100];
printf("Enter an expression:\n");
gets(A);
printf("\nExpression entered is:\n");
puts(A);
create(&o, A);
if (parenthesis_matcher(&o, A) == 1)
{
printf("Parenthesis are balanced!\n");
}
else
{
printf("Parenthesis are not balanced!\n");
}
}
/*In parenthesis matching,we assume that ) appears only when atleast one ( must be
present before it. So, if ) appears at first element in a string ,we straight-away
say that it is not matched.*/