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 some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks, and should create a new stack once the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.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.
A:
思路:用一个stack的数组,每个stack的容量都固定。如果当前stack已经full, 就push进入下一个stack。
FOLLOW UP:
不考虑popAt之后的空闲空间。push的时候,就在当前栈即可,与上面的没有差别。在pop和top的时候略有不同,需要确定要访问的栈不为空。
#include <iostream>
using namespace std;
const int STACK_SIZE = 100;
const int STACK_NUM = 10;
class stack{
private:
int *buf;
int capacity;
int cur;
public:
stack(int c = STACK_SIZE) {
capacity = c;
buf = new int[c];
cur = -1;
}
~stack(){
delete[] buf;
}
void push(int val) {
if (cur == this->capacity) {
cout<<"the stack is full!"<<endl;
return ;
}
buf[++cur] = val;;
}
void pop() {
cur--;
}
int top() {
if (cur == -1) {
cout<<"the stack is empty!"<<endl;
return 0;
}
return buf[cur];
}
bool empty() {
return cur==-1;
}
bool full() {
return cur == capacity-1;
}
};
class SetOfStacks1{
private:
stack *st;
int capacity;
int cur;
public:
SetOfStacks1(int capa = STACK_NUM) {
capacity = capa;
st = new stack[STACK_NUM];
cur = 0;
}
~SetOfStacks1() {
delete[] st;
}
void push(int val) {
if (st[cur].full()) {
cur++;
}
st[cur].push(val);
}
void pop() {
if (st[cur].empty()) {
cur--;
}
st[cur].pop();
}
int top() {
if (st[cur].empty()) {
cur--;
}
st[cur].top();
}
bool empty() {
if (cur == 0) {
return st[cur].empty();
}
return false;
}
bool full() {
if (cur == capacity - 1) {
return st[cur].full();
}
return false;
}
};
class SetOfStacks2{
private:
stack *buf;
int capacity;
int cur;
public:
SetOfStacks2(int capa = STACK_NUM) {
capacity = capa;
buf = new stack[STACK_NUM];
cur = 0;
}
~SetOfStacks2() {
delete[] buf;
}
void push(int val) {
if (buf[cur].full()) {
cur++;
}
buf[cur].push(val);
}
void pop() {
while (buf[cur].empty()) cur--;
buf[cur].pop();
}
void popAt(int num) {
while (buf[num].empty()) num--;
buf[num].pop();
}
int top() {
while (buf[cur].empty()) cur--;
buf[cur].top();
}
bool empty() {
while (cur >= 0 && buf[cur].empty()) cur--;
if (cur == -1) {
return true;
}
return false;
}
bool full() {
if (cur == capacity - 1) {
int tmp = cur;
while (tmp >= 0 && buf[tmp].full()) tmp--;
if (tmp == -1) {
return true;
}
return false;
}
return false;
}
};
int main(){
SetOfStacks2 ss1;
for(int i=0; i<3*STACK_SIZE+1; ++i){
ss1.push(i);
}
for(int i=0; i<STACK_SIZE; ++i){
ss1.popAt(0);
//ss1.popAt(1);
ss1.popAt(2);
}
ss1.popAt(3);
while(!ss1.empty()){
cout<<ss1.top()<<endl;
ss1.pop();
}
}