-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.cpp
108 lines (90 loc) · 2.37 KB
/
stack.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
#include <iostream>
#include <stack>
using namespace std;
void basic_stack()
{
stack<int> newStack;
newStack.push(5);
newStack.push(44);
newStack.push(34);
cout << "Is stack empty? " << newStack.empty() << endl;
cout << "Stack Size? " << newStack.size() << endl;
cout << "Top Element? " << newStack.top() << endl;
cout << "Popping last element..." << endl;
newStack.pop();
cout << "New top element? " << newStack.top() << endl;
cout << "New Size? " << newStack.size() << endl;
}
void balance_check(string symbolString)
{
stack<string> s;
bool balanced = true;
int index = 0;
int str_len = symbolString.length();
while (index < str_len && balanced)
{
string symbol;
symbol = symbolString[index];
if (symbol == "(")
s.push(symbol);
else if (symbol == ")")
if (s.empty())
balanced = false;
else
s.pop();
index++;
}
cout << symbolString << " balanced? " << (balanced && s.empty()) << endl;
}
bool inString(string symbol, string symbols)
{
return symbols.find(symbol) != string::npos;
}
bool matches (string open, string close)
{
string opens = "({[";
string closes = ")]}";
return inString(open, opens) == inString(close, closes);
}
void multi_balance_check(string symbolString)
{
stack<string> s;
bool balanced = true;
int index = 0;
int stringLength = symbolString.length();
while (index < stringLength && balanced)
{
string symbol;
symbol = symbolString[index];
string opens = "({[";
string closes = ")]}";
if (inString(symbol, opens))
s.push(symbol);
else if (inString(symbol, closes))
{
if (s.empty())
balanced = false;
else
{
string top = s.top();
s.pop();
if (!matches(top, symbol))
{
balanced = false;
break;
}
}
}
index++;
}
cout << symbolString << "multi-balanced? " << (balanced && s.empty()) << endl;
}
void test_stack()
{
basic_stack();
balance_check("(())");
balance_check("()()())");
balance_check("(((()))(");
multi_balance_check("({[]})");
multi_balance_check("({[)}");
}