forked from sanketpatil02/Code-Overflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Balanced Parenthesis by using Stacks
94 lines (94 loc) · 1.53 KB
/
Balanced Parenthesis by using Stacks
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
/*
* C++ Program to Check for balanced parenthesis by using Stacks
*/
#include <iostream>
#include <conio.h>
using namespace std;
struct node
{
char data;
node *next;
}*p = NULL, *top = NULL, *save = NULL,*ptr;
void push(char x)
{
p = new node;
p->data = x;
p->next = NULL;
if (top == NULL)
{
top = p;
}
else
{
save = top;
top = p;
p->next = save;
}
}
char pop()
{
if (top == NULL)
{
cout<<"underflow!!";
}
else
{
ptr = top;
top = top->next;
return(ptr->data);
delete ptr;
}
}
int main()
{
int i;
char c[30], a, y, z;
cout<<"enter the expression:\n";
cin>>c;
for (i = 0; i < strlen(c); i++)
{
if ((c[i] == '(') || (c[i] == '{') || (c[i] == '['))
{
push(c[i]);
}
else
{
switch(c[i])
{
case ')':
a = pop();
if ((a == '{') || (a == '['))
{
cout<<"invalid expr!!";
getch();
}
break;
case '}':
y = pop();
if ((y == '[') || (y == '('))
{
cout<<"invalid expr!!";
getch();
}
break;
case ']':
z = pop();
if ((z == '{') || (z == '('))
{
cout<<"invalid expr!!";
getch();
}
break;
}
}
}
if (top == NULL)
{
cout<<"balanced expr!!";
}
else
{
cout<<"string is not valid.!!";
}
getch();
}