-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrackets.c
125 lines (111 loc) · 2.2 KB
/
brackets.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
120
121
122
123
124
125
//This is my practice for NESO Academy, Video #300 - C programming and data structures course in Youtube.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
char stack[MAX];
int top = -1; // indicates stack is empty
//prototypes
void push(char);
char pop(void);
int isFull();
int isEmpty();
int peek_top();
int check_balanced(char *s);
int match_char(char a, char b);
int main(void)
{
char expression[MAX];
int balanced;
printf("Input string to check if brackets match \n");
fgets(expression, MAX, stdin);
balanced = check_balanced(expression);
if (balanced == 1)
printf("The expression is valid\n");
else
printf("The expression is NOT valid\n");
return 0;
}
int check_balanced(char *s)
{
int i;
char temp;
for (i = 0; i < strlen(s); i++)
{
if (s[i] == '{' || s[i] == '[' || s[i] == '(')
push(s[i]);
if (s[i] == '}' || s[i] == ']' || s[i] == ')')
{
if (isEmpty())
{
printf("Right brackets are more than left brackets\n");
return 0;
}
else
{
temp = pop();
if (!match_char(temp, s[i]))
{
printf("Brackets type mismatch\n");
return 0;
}
}
}
}
if (isEmpty())
{
printf("The expression is balanced\n");
return 1;
}
else
{
printf("Left brackets are more than right brackets\n");
return 0;
}
}
int match_char(char a, char b)
{
if (a == '[' && b == ']')
return 1;
if (a == '(' && b == ')')
return 1;
if (a == '{' && b == '}')
return 1;
return 0;
}
void push(char c)
{
if (isFull())
{
printf("Stack Overflow\n");
exit(1);
}
top++;
stack[top] = c;
}
char pop(void)
{
char c;
if (isEmpty())
{
printf("Stack Underflow\n");
exit(1);
}
c = stack[top];
top--;
return c;
}
int isFull()
{
if (top == MAX - 1)
return 1;
else
return 0;
}
int isEmpty()
{
if (top == -1)
return 1;
else
return 0;
}