看到這麼牛逼的模板哭了

來源:互聯網
上載者:User

#include<ostream>
#include<iostream>
#include<cstdlib>
 
using namespace std;
 
template<class T>
class Node
{
public:
  T data;
  Node<T> *next;
  Node(T d = T(),Node<T> *n=NULL): data(d), next(n)
  {} 
};
 
 
template <class T>
class CirHSLinkedList
{
public:
  Node<T> head; 
  CirHSLinkedList();
  ~CirHSLinkedList()
  {
    clear();
  }
  CirHSLinkedList(T const value[],int n);
  bool isEmpty() const;
  void clear();
  CirHSLinkedList<T>& operator=(CirHSLinkedList<T>  const &list);
  CirHSLinkedList(CirHSLinkedList<T> const &list);
  template <typename U>
  friend ostream & operator << (ostream & out,CirHSLinkedList<U>const &list);
};
 
template<class T>
CirHSLinkedList<T>::CirHSLinkedList(T const value[],int n)
{
  Node<T>*temp= &head;
  for(int i=0;i<n;i++)
  {
    temp->next = new Node<T>(value[i]);
    temp=temp->next;
  }
 
}
template<class T>
CirHSLinkedList<T>::CirHSLinkedList()
{
}
 
template<class T>
bool CirHSLinkedList<T>::isEmpty() const
{
  return 0 == head->next;
}
template<class T>
void CirHSLinkedList<T>::clear()
{
    Node<T> *p =  head.next;
    while(p)
    {
      Node<T> *q=p;
      p=p->next;
      delete q;
    }
    head.next =  NULL;
}
 
template<class T>
CirHSLinkedList<T>& CirHSLinkedList<T>:: operator=(CirHSLinkedList<T> const &list)
{
  if(this == &list) return *this; //avoid self asignment
  clear();
  Node<T> *rear= &head;
  for(Node<T> *p=list.head.next;p ;p = p->next)//change to NULL 
  {
    rear->next=new Node<T>(p->data);
    rear=rear->next;
  }
  return *this;
}
 
template<class T>
CirHSLinkedList<T>::CirHSLinkedList(CirHSLinkedList<T> const &list)
{
  *this=list;
}
template<typename T>
ostream & operator << (ostream & ot,CirHSLinkedList<T>  const &list)
{
  Node<T> *p=list.head.next;
  ot<<"(";
  while(p!=NULL)
  {
    ot<<p->data;
    p=p->next;
    if(p!=NULL)
      ot<<",";
  }
  ot<<")\n";
  return ot;
}
 
int main()
{
  CirHSLinkedList<char> lista("abc",3);
  CirHSLinkedList<char> listb(lista);
  cout  << lista;
  return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.