-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q2.cpp
93 lines (84 loc) · 2.03 KB
/
Q2.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
#include<iostream>
#include<string>
using namespace std;
struct Node {
int data;
Node* next;
//constructor
Node(int data) {
this->data = data;
this->next = NULL;
}
};
class Stack {
private:
Node* top;
public:
Stack() {
top = NULL;
}
// Push method
void push(int d) {
Node* newnode = new Node(d);
newnode->next = top;
top = newnode;
}
// Pop and return value
int pop() {
if (isempty()) {
cout << "Stack underflow!" << endl;
return -1; // Return a default value indicating failure
}
int popvalue = top->data;
Node* temp = top;
top = top->next;
delete temp;
return popvalue;
}
// Peek
int peek() {
if (isempty()) {
cout << "Stack is empty" << endl;
return -1; // Return a default value indicating failure
}
return top->data;
}
bool isempty() {
return top == NULL;
}
};
bool check(string exp) {
Stack my;
for (int i = 0; i < exp.length(); i++) {
char c = exp[i];
if (c == '(' || c == '{' || c == '[') {
my.push(c);
}
else if (c == ')' || c == '}' || c == ']') {
if (my.isempty()) {
return false; // No opening parenthesis to match
}
else if ((c == ')' && my.peek() == '(') ||
(c == '}' && my.peek() == '{') ||
(c == ']' && my.peek() == '[')) {
my.pop();
}
else {
return false; // Mismatched parenthesis
}
}
}
return my.isempty(); // True if stack is empty (all parenthesis matched)
}
int main() {
string exp;
cout<<"enter your expression to check Parenthese "<<endl;
getline(cin,exp);
if (check(exp)) {
cout << "Parentheses are balanced" << endl;
}
else {
cout << "Parentheses are not balanced" << endl;
}
return 0;
}