《21天学通C++》第三周复习清单(二)

2014-11-24 13:01:32 · 作者: · 浏览: 2
sNext = 0;

}

// Returns NULL if no next Node

template

Node * Node::GetNext() const

{

return itsNext;

}

template

T * Node::GetObject() const

{

if (itsObject)

return itsObject;

else

throw NullNode();

}

// **************** List ************

// Generic list template

// Works with any numbered object

// **********************************

template

class List

{

public:

List();

~List();

T* Find(int & position, int ObjectNumber) const;

T*GetFirst() const;

voidInsert(T *);

T*operator[](int) const;

intGetCount() const { return itsCount; }

private:

Node * pHead;

int itsCount;

};

// Implementations for Lists...

template

List::List():

pHead(0),

itsCount(0)

{}

template

List::~List()

{

delete pHead;

}

template

T*List::GetFirst() const

{

if (pHead)

return pHead->itsObject;

else

throw EmptyList();

}

template

T*List::operator[](int offset) const

{

Node* pNode = pHead;


if (!pHead)

throw EmptyList();


if (offset > itsCount)

throw BoundsError();


for (int i=0;i

pNode = pNode->itsNext;


return pNode->itsObject;

}

// find a given object in list based on its unique number (id)

template

T*List::Find(int & position, int ObjectNumber) const

{

Node * pNode = 0;

for (pNode = pHead, position = 0;

pNode!=NULL;

pNode = pNode->itsNext, position++)

{

if (pNode->itsObject->GetObjectNumber() == ObjectNumber)

break;

}

if (pNode == NULL)

return NULL;

else

return pNode->itsObject;

}

// insert if the number of the object is unique

template

void List::Insert(T* pObject)

{

Node * pNode = new Node(pObject);

Node * pCurrent = pHead;

Node * pNext = 0;


int New = pObject->GetObjectNumber();

int Next = 0;

itsCount++;


if (!pHead)

{

pHead = pNode;

return;

}

<