Last active
December 26, 2015 18:49
-
-
Save aaani/7197052 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stack> | |
#include <vector> | |
using namespace std; | |
class SetOfStacks{ | |
vector<stack<int>> stacks; | |
int threshold; | |
public: | |
//Contructor, set the maximum size for each stack | |
SetOfStacks(int lim){ | |
if(lim<2){ | |
throw "Couldn't initialize SetOfStacks. threshold should be greater than 1."; | |
} | |
threshold=lim; | |
} | |
//Method to insert a value to SetOfStacks | |
void insert(int value){ | |
//Add a new stack to the top | |
if(stacks.size() == 0 || stacks.back().size()==threshold){ | |
stacks.push_back(stack<int> ()); | |
} | |
//Push the value to the top of top stack | |
stacks.back().push(value); | |
} | |
//Method to remove a value from SetOfStacks | |
void pop(){ | |
if(stacks.size()>0){ | |
//Remove the top element from the last stack | |
stacks.back().pop(); | |
//Remove the top stack if it's empty | |
if(stacks.back().size()==0) stacks.pop_back(); | |
} | |
} | |
//Method to read top of the SetOfStacks | |
int top(){ | |
if(stacks.size()>0){ | |
return stacks.back().top(); | |
} | |
throw "Empty stack"; | |
} | |
}; | |
//Testing | |
int main(int argc, const char * argv[]) | |
{ | |
SetOfStacks *hstack = new SetOfStacks(2); | |
hstack->insert(-43); | |
hstack->insert(3); | |
hstack->insert(56); | |
hstack->insert(92); | |
hstack->insert(52); | |
hstack->pop(); | |
cout<<hstack->top(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment