-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack_withIsBalancedString.cpp
120 lines (117 loc) · 1.92 KB
/
Stack_withIsBalancedString.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
Given an expression containing opening and closing braces, brackets, and parentheses;
implement a function “isBalanced” to check whether the given expression is a balanced
expression or not, using your stack implementation. For example, {[{}{}]}[()], {{}{}}, and []{}()
are balanced expressions, but {()}[) and {(}) are not balanced. In your main function test your
function using the given examples. bool isBalanced(string exp)
*/
#include<iostream>
using namespace std;
template <typename T>
class stack
{
T* arr = 0;
int c_size, maxsize, top;
public:
stack(int maxsize = 5)
{
this->maxsize = maxsize;
arr = new T[maxsize];
c_size = 0;
top = -1;
}
~stack()
{
if (arr != 0)
{
delete[] arr;
arr = 0;
}
}
bool isEmpty()
{
if (c_size == 0)
return true;
return false;
}
bool isFull()
{
if (c_size == maxsize)
return true;
return false;
}
bool push(T value)
{
if (isFull())
return false;
else
{
top++;
arr[top] = value;
c_size++;
return true;
}
}
bool pop()
{
if (isEmpty())
return false;
else
{
c_size--;
top--;
return true;
}
}
bool getTopValue(T& value)
{
if (isEmpty())
return false;
else
{
value = arr[top];
return true;
}
}
bool isBalanced(string exp)
{
if (isEmpty() && exp[0] == ')' || exp[0] == '}' || exp[0] == ']' || maxsize % 2 != 0)
return false;
for (int i = 0; i < maxsize; i++)
{
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
{
push(exp[i]);
}
else if (arr[top] == '(' && exp[i] == ')' || arr[top] == '{' && exp[i] == '}' || arr[top] == '[' && exp[i] == ']')
{
pop();
}
}
if (isEmpty())
{
return true;
}
else
{
return false;
}
}
};
int main()
{
string a;
cout << "enter string : "; cin >> a;
int size = a.length();
stack <char>s1(size);
if (s1.isBalanced(a))
{
cout << "Balanced";
}
else
{
cout << "not Balanced";
}
system("pause>nul");
return 0;
}