-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetOfStacks.cpp
More file actions
125 lines (106 loc) · 2.42 KB
/
Copy pathSetOfStacks.cpp
File metadata and controls
125 lines (106 loc) · 2.42 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
125
//
// main.cpp
// InterviewPrep
//
// Created by Clifton Gordon on 11/24/15.
// Copyright © 2015 Clifton Gordon. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class SetOfStacks
{
private:
vector<vector<T>> stacks;
int capacity;
public:
SetOfStacks(int c) : capacity(c) {}
virtual ~SetOfStacks() {}
void push(T item)
{
if (stacks.empty() || (stacks.back().size() >= capacity))
{
stacks.push_back(vector<T>());
}
stacks.back().push_back(item);
}
T pop()
{
return popAt(stacks.size() - 1);
}
T popAt(int stackIndex)
{
if (stacks.empty() || (stackIndex >= stacks.size()) || stacks[stackIndex].empty())
{
throw;
}
T value = stacks[stackIndex].back();
stacks[stackIndex].pop_back();
while (!stacks.empty() && stacks.back().empty())
{
stacks.pop_back();
}
return value;
}
void print()
{
if (stacks.empty())
{
cout << "Empty!" << endl;
return;
}
int i = 0;
for (vector<int> v: stacks)
{
cout << "Stack[" << i << "]: ";
bool first = true;
for (int item: v)
{
if (!first)
{
cout << ", ";
}
cout << item;
first = false;
}
cout << endl;
i++;
}
}
};
template <class T>
void PopAtTest(SetOfStacks<T> &s, int stackIndex, int count)
{
cout << "PopAt(" << stackIndex << ") " << count << " times..." << endl;
for (int i = 0; i < count; i++)
{
cout << "Value: " << s.popAt(stackIndex) << endl;
s.print();
}
}
int main(int argc, const char * argv[]) {
SetOfStacks<int> s(3);
for (int i = 0; i < 13; i++)
{
s.push(i);
}
s.print();
for (int i = 0; i < 6; i++)
{
cout << "Popping value " << s.pop() << endl;
s.print();
}
for (int i = 100; i < 107; i++)
{
cout << "Pusing value " << i << endl;
s.push(i);
s.print();
}
PopAtTest(s, 3, 3);
PopAtTest(s, 4, 2);
PopAtTest(s, 0, 3);
PopAtTest(s, 2, 3);
PopAtTest(s, 1, 3);
return 0;
}