-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.cpp
More file actions
124 lines (78 loc) · 2.37 KB
/
Stack.cpp
File metadata and controls
124 lines (78 loc) · 2.37 KB
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
121
122
123
124
#include "Stack.h"
#include "Exceptions.h"
#include <string>
#include <iostream>
using namespace std;
// Creates a Stack class.
//
Stack::Stack(){
top = nullptr;
}
// Puts a character at the top of the stack.
//
void Stack::push(char data){
Node *newNode = new Node;
newNode->data = data;
if (top == nullptr) {
top = newNode;
newNode->next = nullptr;
} else {
newNode->next = top;
top = newNode;
}
}
// Removes from the top of the stack. Throws an EmptyStackException if the stack is empty.
//
void Stack::pop(){
Node *nodeToPop;
if (top == nullptr) {
throw EmptyStackException();
} else {
nodeToPop = top;
top = top->next;
delete nodeToPop;
}
}
// Checks if the stack is empty.
//
bool Stack::isEmpty(){
if (top == nullptr) {
return true;
}
return false;
}
// Scans through the stack and checks if brackets are balanced.
// Creates a stack that only holds brackets. Brackets are added if
// the stack is empty or if the current bracket found does not
// pair with the top of the temp stack. Removes if a balanced pair
// is found. At the end of searching, if the temp stack is empty,
// returns true. Otherwise, returns false.
//
bool Stack::isBalanced(){
Stack temp;
Node* current = top;
while (current != nullptr) {
if (((current->data) == '(') || ((current->data) == ')') ||
((current->data) == '[') || ((current->data) == ']') ||
((current->data) == '{') || ((current->data) == '}')) {
if (temp.isEmpty()) {
temp.push(current->data);
} else if ((((temp.top)->data) == '(' && ((current->data) == ')')) ||
(((temp.top)->data) == '{' && ((current->data) == '}')) ||
(((temp.top)->data) == '[' && ((current->data) == ']'))) {
temp.pop();
} else {
temp.push(current->data);
}
current = current->next;
// If a character is not a bracket, it is ignored.
//
} else {
current = current->next;
}
}
if (temp.isEmpty()) {
return true;
}
return false;
}