3.3 Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds same threshold. Implement a data structureSetOfStacksthat mimics this. SetOfStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity.SetOfStacks.push() andSetOfStacks.pop() should behave identically to a single stack (that is,pop() should return the same values as it would if there were just a single stack).
FOLLOW UP
Implement a function popAt(int index) which performs a pop operation on a specific sub-stack.
template <typename T>
class SetOfStacks {
private:
vector<stack<T> > stacks;
public:
int getLastIndex() {
return stacks.size() - 1;
}
void push(const T &value) {
int lastIndex = getLastIndex();
if (lastIndex != -1 && stacks[lastIndex].size() < 100) {
stacks[lastIndex].push(value);
} else {
stack<T> s;
s.push(value);
stacks.push_back(s);
}
}
T pop() {
int lastIndex = getLastIndex();
if (lastIndex != -1) {
T value = stacks[lastIndex].top();
stacks[lastIndex].pop();
if (stacks[lastIndex].empty()) {
stacks.pop_back();
}
return value;
}
}
};
FOLLOW UP