双链表的实现

Posted Misli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了双链表的实现相关的知识,希望对你有一定的参考价值。

双链表:可以从一个表结点出发,在线性表中随意访问它的前驱结点和后继结点,双链表有两个指针。

双链表结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++;
    }
}

  

以上是关于双链表的实现的主要内容,如果未能解决你的问题,请参考以下文章

数据结构 双链表的简单理解和基本操作

基础数据结构---双链表go语言的代码实现

基础数据结构---双链表go语言的代码实现

有序的双链表的实现

数据结构初阶第四篇——双链表(实现+图解)

双链表的实现