考慮到設計需要,我們需要提供下面的4個類:
(1)List類本身。它包含連接到兩端的鏈接,表的大小以及一系列方法。
(2)Node類。該類看起來是私有的嵌套類。一個節點包含數據和用來指向其前和其後的結點的指針,以及適當的構造函數。
(3)const_iterator類。該類抽象了位置的概念。
(4)iterator類。
template <typename Object>
class List
{
private:
struct Node
{ };
public:
class const_iterator { };
class iterator:public const_iterator{ };
public:
List()
{ }
List(cosnt List & rhs)
{ }
~List() { }
const List & operator= (const List & rhs)
{ }
iterator begin()
{ return iterator(head->next);}
const_iterator begin() const
{ return const_iterator(head->next); }
iterator end()
{ return iterator( tail);}
const_iterator end() const
{retrun const_iterator(tail); }
int size()
{ return theSize;}
bool empty( ) const
{ return size() == 0; }
void clear()
{
while(!empty())
por_front( );
}
Object & front()
{ retrun *begin();}
const Object & front() const
{ return *begin();}
Object & back()
{ return *--end(); }
const Object & back() const
{ return 8--end(); }
void push_front(const Object* x)
{ insert(begin(),x);}
void push_back(const Obect & x)
{ insert(end(),x); }
void pop_front( )
{ erase(begin()):}
void pop_back()
{ erase(--end()); }
iterator insert( iterator itr,const Object & x)
{ }
iterator erase(iterator itr)
{ }
iterator erase(iterator start, iterator end)
{ }
private:
int theSize;
Node * head;
Node * tail;
void init()
{ }
};
Node 類
struct Node
{
Object data;
Node *prev;
Node
Node(const Obejct & d=Object(),Node *p=NULL,Node *n=NULL):data(d),prev(p),next(n){}
};
常迭代器類
治理要注意一下operator++的實現。在語法上前綴和後綴版本的operator++是完全不同的。因此,需要對不同的形式分別來編寫例程。他們擁有相同的名字,因此必須用不同的符號來區分。C++需要通過給前綴形式指定空參數表,給後綴形式指定一個匿名的int參數來富裕前綴和後綴形式以不同的標識。然後,++itr掉頭、用另參數operator++;而itr++調用單參數operator++。這個int參數永遠也不使用,其存在的意義僅僅在於給出一個不同的標識,使用前綴的形式要快於使用後綴的形式。
class const_iterator
{
publicL
const_iterator( ):current(NULL)
{ }
const Obejct & operator* ( ) const
{ return retieve(); }
const_iterator & operator++ ( )
{
current=current->next;
retrun *this;
}
iterator operator++(int )
{
iterator old=*this;
++(*this);
return old;
}
protected:
iterator(Node *p):const_iterator(p){ }
friend class List<Object>;
};
iterator類 他繼承自const_iterator
class iterator:public const_iterator
{
public:
iterator() { }
object & operator*( )
{ return retrieve(); }
const Object & operator *( ) const
{ return const_iterator::operator*(); }
iterator & operator++()
{
current=current->next;
return *this;
}
iterator operator++(int)
{
iterator old=*this;
++(*this):
return old;
}
protected:
iterator(Node*p) : const_iterator(p)
{}
friend class List<Object>;
};
List類的構造函數,三大函數和私有init例程
List()
{ init() ; }
~List()
{
clear();
delete head;
delete tail;
}
List(const List & rhs)
{
init();
*this=rhs;
}
cosnt List & operator= (const List & rhs )
{
if( this == &rhs)
retrun *this;
clear();
for(const_iterator itr=rhs.begin();itr !=rhs.end();++itr)
push_back( *itr);
return *this;
}
void init()
{
thsSize=0;
head=new Node;
tail=new Node;
head->next=tail;
tail->prev=head;
}