-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparenthesisMatch.c
More file actions
96 lines (82 loc) · 2.02 KB
/
parenthesisMatch.c
File metadata and controls
96 lines (82 loc) · 2.02 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define MAX 100
// A structure to represent a stack
struct Stack {
int top;
int maxSize;
char* array;
};
struct Stack* create(char max)
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->maxSize = max;
stack->top = -1;
stack->array = (char*)malloc(stack->maxSize * sizeof(char));
// here above memory for array is being created
// size would be 10*4 = 40
return stack;
}
int isFull(struct Stack* stack)
{
if(stack->top == stack->maxSize - 1){
printf("Will not be able to push maxSize reached\n");
}
// Since array starts from 0, and maxSize starts from 1
return stack->top == stack->maxSize - 1;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
void push(struct Stack* stack, char item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
}
void pop(struct Stack* stack)
{
if (isEmpty(stack))
return;
stack->array[stack->top--];
}
int peek(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}
bool checkPair(char val1,char val2){
return (( val1=='(' && val2==')' )||( val1=='[' && val2==']' )||( val1=='{' && val2=='}' ));
}
bool checkBalanced(struct Stack* stack, char expr[], int len){
for (int i = 0; i < len; i++)
{
if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{')
{
push(stack, expr[i]);
}
else
{
if (isEmpty(stack))
return false;
else if(checkPair(peek(stack),expr[i]))
{
pop(stack);
continue;
}
return false;
}
}
return true;
}
int main() {
char exp[MAX] = "({})[]";
int len = strlen(exp);
struct Stack* stack = create(len);
checkBalanced(stack, exp, len)?printf("Balanced"): printf("Not Balanced");
return 0;
}