码迷,mamicode.com
首页 > 其他好文 > 详细

双链表的实现

时间:2016-03-29 23:48:58      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

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

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

  

双链表的实现

标签:

原文地址:http://www.cnblogs.com/Misli/p/5335160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!