C++ 循环链表基本算法
#ifndef CLinkList_h#define CLinkList_h#includeusing namespace std;template struct Node{ T data; struct Node * next;};template class CLinkList{public: CLinkList(){rear = new Node ; rear ->next = rear;} CLinkList(T a[], int n); ~CLinkList(); int GetLength(); Node * Get(int i); int Locate(T x); void Insert(int i, T x); T Delete( int i); void PrintList(); void Connect(CLinkList &b);private: Node *rear;};template CLinkList ::CLinkList(T a[], int n){ rear = new Node ; rear->next = rear; for(int i = 0;i< n;i++){ Node * s = new Node ; s->data = a[i]; s->next = rear->next; rear->next = s; }}template CLinkList ::~CLinkList(){ rear = rear->next; Node *p = rear->next; Node *q; while(p!=rear){ q = p->next; delete p; p = q; //delete rear; } rear->next = rear;}template int CLinkList ::GetLength(){ if(rear->next == rear) return 0; Node * p = rear->next; int j = 0; while (p!= rear){ p= p->next; j++; } return j;}template Node * CLinkList ::Get(int i){ if(i<1) throw " 查找位置错误"; Node * p = rear; for(int j = 0; j< i;j++){ p = p->next; } return p; }template int CLinkList :: Locate(T x){ Node * p = rear->next; int j = 1; while(p!= rear){ if(p->data == x){ return j; }else{ p = p->next; j++; } } return -1;}template void CLinkList ::Insert(int i, T x){ if(i<1 || i> GetLength()) throw"位置插入错误"; Node * p = rear; p = Get(i); Node *s = new Node ; s->data = p->data; s->next = p->next; p->next = s; p->data = x;}template T CLinkList :: Delete( int i){ if(i<1 || i> GetLength()) throw"位置错误"; Node * p = rear->next; int j = 1; while(j next; j++; } Node * s = p->next; p->next = s->next; if(s == rear){ rear = p; } T x = s->data; return x; }template void CLinkList :: PrintList(){ Node *p = rear->next; if(p->next == rear) {cout<< "链表为空列表!"< data<<" "; p= p->next; } cout << endl;}template void CLinkList ::Connect(CLinkList &b){ Node *q = b.rear->next; b.rear->next = rear->next; rear->next = q->next; rear = b.rear; delete q;}#endif /* CLinkList_h */