-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathparanthisis_matching.c
109 lines (101 loc) · 1.89 KB
/
paranthisis_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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack
{
int top;
int size;
char *arr;
};
int empty(struct stack *s)
{
if (s->top == -1)
{
return 1;
}
return 0;
}
void push(struct stack *s, char val)
{
s->top++;
s->arr[s->top] = val;
}
char pop(struct stack *ptr)
{
char val = ptr->arr[ptr->top];
ptr->top--;
return val;
}
int matched(char popped, char opening)
{
if (popped == '(' && opening == ')')
{
return 1;
}
else if (popped == '[' && opening == ']')
{
return 1;
}
else if (popped == '{' && opening == '}')
{
return 1;
}
return 0;
}
int paranthesis(char *exp)
{
struct stack sp;
int size = strlen(exp);
sp.size = size; // Set the size as needed
sp.top = -1;
sp.arr = (char *)malloc(sp.size * sizeof(char));
for (int i = 0; exp[i] != '\0'; i++)
{
if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{')
{
push(&sp, exp[i]);
}
else if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}')
{
if (empty(&sp))
{
return 0;
}
char val = pop(&sp);
if (!matched(val, exp[i]))
{
if (empty(&sp))
{
free(sp.arr);
return 0;
}
val = pop(&sp);
}
}
}
if (empty(&sp))
{
return 1;
}
else
{
return 0;
}
free(sp.arr); // Free allocated memory
}
int main()
{
char exp[100];
printf("Enter an expression\n=");
scanf("%s", exp);
if (paranthesis(exp))
{
printf("The Expression \"%s\" has equal paranthesis\n", exp);
return 0;
}
else
{
printf("The Expression \"%s\" has unequal paranthesis\n", exp);
}
return 0;
}