双向链表实现

 

template <class type>
class link
{
 private:
  static link<type>* freelist;
 public:
  type element;
  link* next;
  link* prev;
  link(const type& a, link* pre = NULL, link* ne = NULL)
  {
   element = a;
   next = ne;
   prev = pre;
  }
  link(link* pre = NULL, link* ne = NULL)
  {
   next = ne;
   prev = pre;
  }
  void* operator new(size_t);
  void operator delete(void* ptr);
  
}

template <class type>
link<type>* link<type>::freelist = NULL;

template <class type>
void* link<type>::operator new(size_t)
{
 if (freelist == NULL)
  return new link;
 link<type>* tmp = freelist;
 freelist = freelist->next;
 return tmp;
}

template <class type>
void link<type>::operator delete(void* ptr)
{
 ((link<type>*)ptr)->next = freelist;
 freelist = (link<type>*)ptr;
}

template <class type>
class list:public link
{
private:
 link<type>* head;
 link<type>* tail;
 link<type>* fence;
 int leftcnt;
 int rightcnt;
 void init()
 {
  fence = head = tail = NULL;
  rightcnt = 0;
  leftcnt = 0;
 }
 void removeall(0
 {
  while (head != NULL)
  {
   fence = head;
   head = head->next;
   delete fence;
  }
 }
public:
 bool insert(const type&);
 bool append(const type&);
 bool remove(type&);
 void prev(void);
}

template <class type>
bool list<type>::insert(const type& item)
{
 fence->next = new link<type>(item, fence, fence->next);
 if (fence->next->next != NULL)
  fence->next->next->prev = fence->next;
 if (tail = fence)
  tail = fence->next;
 rightcnt++;
 return true;
}

template <class type>
bool list<type>::append(const type& item)
{
 tail = tail->next = new link<type>(item, tail, NULL);
 rightcnt++;
 return true;
}

template <class type>
bool list<type>::remove(type& item)
{
 if (fence->next == NULL)
  return false;
 item = fence->next->element;
 link<type>* tmp = fence->next;
 if (tmp->next != NULL)
  tmp->next->prev= fence;
 else
  tail = fence;
 fence->next = tmp->next;
 delete tmp;
 right--;
 return true;
}

template <class type>
void list<type>::prev()
{
 fence = fence->prev;
 rightcnt++;
 leftcnt--;
}

你可能感兴趣的:(双向链表)