Cracking The Coding Interview3.3

时间:2023-03-08 19:51:20
//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.
// //#include "mStack.h"
#include "MyStack.h"
struct stackPoint
{
MyStack *currentStack;
stackPoint *nextStackPoint;
}; class SetOfStacks
{
public:
SetOfStacks()
{
sp = new stackPoint;
sp->currentStack = new MyStack;
sp->nextStackPoint = NULL;
numOfStack = 1;
} bool push(int e)
{
if (sp->currentStack->isFull())
{ stackPoint *t = new stackPoint;
t->currentStack = new MyStack;
t->currentStack->push(e); t->nextStackPoint = sp;
sp = t;
numOfStack ++;
}
else
{
sp->currentStack->push(e);
}
return true;
} int pop()
{
if (sp->currentStack->isEmpty())
{
stackPoint *t =sp;
sp = sp->nextStackPoint;
delete t;
numOfStack --;
return sp->currentStack->pop();
}
else
{
return sp->currentStack->pop();
}
} int popAt(int index)
{
int ind = numOfStack - index;
if (ind <0)
{
return -9999;
} stackPoint *t = sp;
while(ind>0)
{
ind--;
t=t->nextStackPoint;
}
return t->currentStack->pop();
} int getNumOfStack()
{
return numOfStack;
} private:
stackPoint *sp;
int numOfStack;
}; int main()
{
SetOfStacks s; for (int i = 0;i<100;i++)
{
s.push(i+1);
}
cout<<"numOfStack "<<s.getNumOfStack();
cout<<endl;
for (int i=0;i<50; i++)
{
cout<<s.pop()<<endl;
}
cout<<"numOfStack "<<s.getNumOfStack()<<endl;
cout<<"PoPat "<<s.popAt(1)<<endl;
return 0;
}

上例子中,popAt()没有把pop位置后面的数据前移。用到的MyStack对stack简单封装了一下,如下,

#include <iostream>
#include <stack>
#define MAXSIZE 20
using namespace std;
class MyStack
{
public:
stack<int> mstack;
void push(int e)
{
mstack.push(e);
}
int pop()
{
if (!mstack.empty())
{
int k=mstack.top();
mstack.pop();
return k;
}
return -1; }
bool isFull()
{
if (mstack.size()>MAXSIZE-1)
{
return true;
}
else
return false;
}
bool isEmpty()
{
return mstack.empty();
}
};