Created
January 24, 2014 02:14
-
-
Save tolinwei/8590913 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 <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