-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpp-data-structures-stack-parens-matching.cpp
120 lines (104 loc) · 1.99 KB
/
cpp-data-structures-stack-parens-matching.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
#include <iostream>
using namespace std;
class Stack {
private:
int size;
int top;
char* S; // array for storing elements in the stack
public:
Stack(int size);
~Stack();
void push(char x);
char pop();
int isFull();
int isEmpty();
int stackTop();
};
Stack::Stack(int size)
{
this->size = size;
top = -1;
S = new char[size];
}
Stack::~Stack() {
delete[] S;
}
void Stack::push(char x) {
if (isFull()) {
cout << "stack overflow" << endl;
}
else {
top++;
S[top] = x;
}
}
char Stack::pop() {
char x = -1;
if (isEmpty()) {
cout << "stack underflow" << endl;
}
else {
x = S[top];
top--;
}
return x;
}
int Stack::isFull() {
if (top == size - 1) {
return 1;
} return 0;
}
int Stack::isEmpty() {
if (top == -1) {
return 1;
}
return 0;
}
int Stack::stackTop() {
if (isEmpty())
return -1;
else
return S[top];
}
int isBalanced(char* exp)
{
Stack st((int)strlen(exp)); // create a stack
for (int i = 0; exp[i] != '\0'; i++) { // process the expression
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[') { // (,{,[ found push to stack
st.push(exp[i]);
}
else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']') { // ),},] found
if (st.isEmpty()) // ) found and stack is empty: unbalanced
return false;
else if ((exp[i] == st.stackTop() + 1) || (exp[i] == st.stackTop() + 2)) // matching the symbols with the top stack ASCII
st.pop();
else
return false;
}
}
return st.isEmpty() ? true : false; // If stack is empty then balanced else unbalanced
}
int main() {
char A[] = "{([a+b]*[c-d])/e}";
if (isBalanced(A)) {
cout << "Matched" << endl;
}
else {
cout << "Not matched" << endl;
}
char B[] = "{([a+b]}*[c-d])/e}";
if (isBalanced(B)) {
cout << "Matched" << endl;
}
else {
cout << "Not matched" << endl;
}
char C[] = "{([{a+b]*[c-d])/e}";
if (isBalanced(C)) {
cout << "Matched" << endl;
}
else {
cout << "Not matched" << endl;
}
return 0;
}