Cracking The Coding Interview3.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.
//

//#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();
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值