《雙向迴圈連結串列STL中的iterator實現》
雙向迴圈連結串列,STL中的iterator實現
帶頭節點的連結串列
在列表頭部引入一個偽首節點來實現,這個節點被稱為頭節點。這個頭節點的資料部分不存放列表元素;它作為存放第一個元素的節點的前驅,其鏈域指向“真正的”首節點。頭節點的作用其實就是在迴圈連結串列中告訴你連結串列的起始位置
Dnode<T> *header=new dnode<T>;
header->prev=header;
header->next=header;
//default constructor
template <typename T>
class dnode
{ public:
Dnode()
{
next=this;
prev=this;
}
}
Template<Typename T>
Void writeDLinkedList(dnode<T>
*header, const string&separator=“ “)
{
Dnode<T> *p=header->next;
While(p!=header)
{
cout<<p->nodeValue<<separator;
p=p->next;
}
}
Template<Typename T>
Dnode<T> *insert(dnode<T> *curr,const
T& item)
{ dnode<T> *newNode, *prevNode;
newNode=new dnode<T>(item);
prevNode=curr->prev;
newNode->prev=prevNode;
newNode->next=curr;
prevNode->next=newNode;
curr->prev=newNode;
return newNode;
}
Template<Typename T>
void *erase(dnode<T> *curr)
{
if(curr->next==curr)return;
dnode<T> *prevNode=curr->prev,
*succNode=curr->next;
prevNode->next=succNode;
succNode->prev=prevNode;
delete curr;
}
STL中的iterator的實現
// d_liter.h
class iterator
{
public:
friend classminiList<T>;
friend classconst_iterator;
iterator() {}
bool operator== (constiterator& rhs) const
{
return nodePtr ==rhs.nodePtr;
}
bool operator!= (constiterator& rhs) const
{
return nodePtr !=rhs.nodePtr;
}
T& operator* ()
{ if (nodePtr->next== nodePtr)
throw
referenceError("miniListiterator: reference error");
returnnodePtr->nodeValue;
}
iterator& operator++() //前++
{ nodePtr =nodePtr->next;
return *this; //return new iterator value
}
iteratoroperator++ (int) //後++
{ iterator tmp = *this;
nodePtr = nodePtr->next;
return tmp; //return original iterator value
}
iterator& operator--()
{
nodePtr =nodePtr->prev;
return *this; //return new iterator value
}
iteratoroperator-- (int)
{
iterator tmp =*this;
nodePtr =nodePtr->prev;
return tmp; //return original iterator value
}
private:
dnode<T> *nodePtr;
iterator(dnode<T> *p):nodePtr(p)
{}
};