Skip to content

Instantly share code, notes, and snippets.

@tolinwei
Created January 24, 2014 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolinwei/8590913 to your computer and use it in GitHub Desktop.
Save tolinwei/8590913 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class SetOfStacks //stacks managed by vector
{
private:
int capacity;
vector<stack<int>> vs;
stack<int> get_last() {
//return vs[vs.size()-1];
return vs.at(vs.size()-1);
}
public:
SetOfStacks(int cap) {capacity = cap;}
void push(int v) {
//cout << vs.size() << endl;
//if no stack, push new stack
if (vs.size() == 0) {
cout << "new vector" << endl;
stack<int> s;
vs.push_back(s);
}
//if current stack's full, push new stack
//imagine maimum is 3
else if (get_last().size() == capacity) {
cout << "add new stack" << endl;
stack<int> s;
vs.push_back(s);
}
stack<int> temp = get_last();
temp.push(v);
vs.pop_back();
vs.push_back(temp);
}
void pop() {
if (vs.size() == 0) {
return;
}
//if last element of the stack, remove the stack from vector
else if (get_last().size() == 1) {
vs.pop_back();
}
//else, normal pop
else {
stack<int> temp = get_last();
temp.pop();
vs.pop_back();
vs.push_back(temp);
}
}
int top() {
if (vs.size() != 0 && get_last().size() != 0) {
return get_last().top();
} else {
return NULL;
}
}
int stack_num() {
return vs.size();
}
};
int main(int argc, char *argv[]) {
//test case
SetOfStacks ss(3);
ss.push(1);
ss.push(2);
ss.push(3);
ss.push(4);
cout << ss.stack_num() << endl;;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment