-
Notifications
You must be signed in to change notification settings - Fork 0
/
Balanced parantheses
100 lines (88 loc) · 2.18 KB
/
Balanced parantheses
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
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 30
int top=-1;
int stack[MAX];
void push(char);
char pop();
int match(char a,char b);
int check(char []);
int main()
{
char exp[MAX];
int valid;
printf("Enter an algebraic expression : ");
gets(exp);
valid=check(exp);
if(valid==1)
printf("Valid expression\n");
else
printf("Invalid expression\n");
return 0;
}
int check(char exp[] )
{
int i;
char temp;
for(i=0;i<strlen(exp);i++)
{
if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[')
push(exp[i]);
if(exp[i]==')' || exp[i]=='}' || exp[i]==']')
if(top==-1)
{
printf("Right parentheses are more than left parentheses\n");
return 0;
}
else
{
temp=pop();
if(!match(temp, exp[i]))
{
printf("Mismatched parentheses are : ");
printf("%c and %c\n",temp,exp[i]);
return 0;
}
}
}
if(top==-1)
{
printf("Balanced Parentheses\n");
return 1;
}
else
{
printf("Left parentheses more than right parentheses\n");
return 0;
}
}
int match(char a,char b)
{
if(a=='[' && b==']')
return 1;
if(a=='{' && b=='}')
return 1;
if(a=='(' && b==')')
return 1;
return 0;
}
void push(char item)
{
if(top==(MAX-1))
{
printf("Stack Overflow\n");
return;
}
top=top+1;
stack[top]=item;
}
char pop()
{
if(top==-1)
{
printf("Stack Underflow\n");
exit(1);
}
return(stack[top--]);
}