-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_expression_balanced.c
More file actions
103 lines (96 loc) · 1.45 KB
/
check_expression_balanced.c
File metadata and controls
103 lines (96 loc) · 1.45 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
97
98
99
100
101
102
103
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<string.h>
struct stack
{
int capacity;
int size;
int top;
char *arr;
};
struct stack *createstack(int n)
{
struct stack *t=(struct stack *)malloc(sizeof(struct stack));
t->arr=(char *)malloc(n*sizeof(char));
t->top=-1;
t->capacity=n;
t->size=0;
return t;
}
void push(struct stack *s,char ele)
{
if(s->size==s->capacity)
{
printf("Stack overflow");
return;
}
s->arr[++s->top]=ele;
s->size=s->size+1;
}
char pop(struct stack *s)
{
char ele;
if(s->size==0)
{
printf("Stack empty\n");
return CHAR_MIN;
}
ele=s->arr[s->top--];
s->size=s->size-1;
return ele;
}
char peek(struct stack *s)
{
if(s->size==0)
{
printf("Stack empty\n");
return CHAR_MIN;
}
return(s->arr[s->top]);
}
int matchstr(char a,char b)
{
if(a=='('&&b==')')
return 1;
if(a=='{'&&b=='}')
return 1;
if(a=='['&&b==']')
return 1;
return 0;
}
int bal(struct stack *s,char *str,int x)
{
int i=0;
while(str[i])
{
if(str[i]=='('||str[i]=='{'||str[i]=='[')
push(s,str[i]);
if(str[i]==')'||str[i]=='}'||str[i]==']')
{
if(s==NULL)
return 0;
if(!matchstr(pop(s),str[i]))
return 0;
}
i++;
}
if(s==NULL)
return 1;
else
return 0;
}
int main()
{
char a[100];
int x;
printf("Enter the string\n");
scanf("%[^\n]s",a);
x=strlen(a);
struct stack *s=createstack(x);
if(bal(s,a,x))
printf("expression is balanced");
else
printf("expression is not balanced");
return 0;
}