-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpractice_parenthesis_match.cpp
96 lines (88 loc) · 1.31 KB
/
practice_parenthesis_match.cpp
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 <bits/stdc++.h>
using namespace std;
class Node
{
public:
char data;
Node *next;
};
class Stack
{
private:
Node *top;
public:
Stack();
~Stack();
void Push(char x);
char Pop();
int isEmpty();
};
Stack ::Stack()
{
top = NULL;
}
Stack::~Stack()
{
Node *p = new Node;
while (top)
{
top = top->next;
delete p;
p = top;
}
}
void Stack ::Push(char x)
{
Node *t = new Node;
if (t == NULL)
cout << "Stack Overflow!";
else
{
t->data = x;
t->next = top;
top = t;
}
}
char Stack ::Pop()
{
Node *p;
char x = -1;
if (top == NULL)
cout << "Stack Underflow!" << endl;
else
{
p = top;
x = p->data;
top = top->next;
delete p;
}
return x;
}
int Stack ::isEmpty()
{
return top ? 0 : 1;
}
int isBalanced(char *exp)
{
Stack stk;
for (int i = 0; i < strlen(exp); i++)
{
if (exp[i] == '(')
stk.Push(exp[i]);
else if (exp[i] == ')')
{
if (stk.isEmpty())
{
return false;
}
else
stk.Pop();
}
}
return stk.isEmpty() ? true : false;
}
int main()
{
char E[] = "(a+b)*(c+d)";
cout << isBalanced(E) << endl;
}