双链表:可以从一个表结点出发,在线性表中随意访问它的前驱结点和后继结点,双链表有两个指针。
双链表结template<class Elem> class Link private: static Link<Elem>* freelist ;//Head of the freelis public:
Elem element;//value for this node Link *next;//pointer to next node in list Link *prev;//pointer to previous node Link(const Elem& e, Link *prevp=NULL,Link *nextp=NULL) { element =e; prev=prevp; next=nextp; } Link(Link* prevp=NULL,Link* nextp=NULL) { prev=prevp; next=nextp; } //Overload new and delete operators for freelist void* operator new(size_t); void opterator delete(void*);
}; template<class Elem> Link<Elem>*Link<Elem>::freelist=NULL; template<class Elem>//Overload for new operator void* Link<Elem>::operator new(size_t){ if(freelist==NULL) return :: new Link;//Create space Link<Elem>* temp=freelist;//can take from freelist freelist=freelist->next; return temp; } template<class Elem>//Overload for delete operator void Link<Elem>::Operator delete(void *ptr){ ((Link<Elem>*)ptr)->next=freelist;//put on freelist freelist=(Link<Elem>*)ptr; }
双链表类insert,append,remove和prev函数的实现
tempate<class Elem>//insert at front of right partition bool LLink<Elem>::insert(const Elem& item){ fence->next=new Link<Elem>(item,fence,fence->next) ; if(fence->next->next!=NULL)//if not deleting at end fence->next->next->prev=fence->next; if(tail==fence) tail=fence->next; rightcnt++; return true; } template<class Elem>//append Elem to end of the list bool LList<Elem>::append(const Elem& item){ tail=tail->next=new Link<Elm>(item,tail,NULL); rightcnt++; return true; } template<class Elem>//remove and return first Elem in right partion bool LList<Elem>::remove(Elem& it){ if(fence->next==NULL) return false;//empty right it=fence->next->element;//remember value Link<Elem>* ltemp=fence->next;//remenber link node if(ltemp->next!=NULL) ltemp->next-prev=fence; else tail=fence;//reset tail fence->next=ltemp->next; delete ltemp; rightcnt--; return true; } template<class Elem>//move fence one step left;no change if left is empty void LList<Elem>::prev(){ if(fence!=head) { fence=fence->prev; leftcnt--; rightcent++; } }