《CITI》P137
3 栈与队列
题目:
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 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.
解答
const int STACK_SIZE = 100; //每个栈的容量
const int STACK_NUM = 10; //栈的数量
class stack{
private:
int *buf; //栈空间
int cur; //栈顶位置
int capacity; //栈容量
public:
stack(int capa = STACK_SIZE){
buf = new int[capa];
cur = -1;
capacity = capa;
}
~stack(){
delete[]buf;
}
void push(int val){
buf[++cur] = val;
}
void pop(){
--cur;
}
int top(){
return buf[cur];
}
bool empty(){
return cur == -1;
}
bool full(){
return cur == capacity - 1;
}
};
class SetOfStacks{ //without popAt()
private:
stack *st;
int cur;
int capacity;
public:
SetOfStacks(int capa = STACK_NUM){
st = new stack[capa];
cur = 0;
capacity = capa;
}
~SetOfStacks(){
delete[]st;
}
void push(int val){
if (full())
return;
if (st[cur].full())
cur++;
st[cur].push(val);
}
void pop(){
if (empty())
return;
if (st[cur].empty())
cur--;
st[cur].pop();
}
int top(){ //调用之前需判断栈是否为空
if (st[cur].empty())
cur--;
return st[cur].top();
}
bool empty(){
return (cur == 0 && st[cur].empty());
}
bool full(){
return (cur == capacity - 1 && st[cur].full());
}
};
class SetOfStacks1{
private:
stack *st;
int cur;
int capacity;
public:
SetOfStacks1(int capa = STACK_NUM){
st = new stack[capa];
cur = 0;
capacity = capa;
}
~SetOfStacks1(){
delete[]st;
}
void push(int val){
if (full())
return;
if (st[cur].full())
cur++;
st[cur].push(val);
}
void pop(){
if (empty())
return;
while (st[cur].empty())
cur--;
st[cur].pop();
}
void popAt(int idx){
if (st[idx].empty())
return;
st[idx].pop();
}
int top(){ //调用之前需判断栈是否为空
while (st[cur].empty())
cur--;
if (cur >= 0)
return st[cur].top();
}
bool empty(){
while (cur != -1 && st[cur].empty())
cur--;
return (cur == -1);
}
bool full(){
return (cur == capacity - 1 && st[cur].full());
}
};