C++ 循环链表基本算法

C++ 循环链表基本算法

#ifndef CLinkList_h
#define CLinkList_h
#include 
using namespace std;
template <class T>
struct Node{
    T data;
    struct Node * next;
};
template <class T>
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 <class T>
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 <class T>
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 <class T>
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 <class T>
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 <class T>
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 <class T>
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 <class T>
T CLinkList:: Delete( int i){
    if(i<1 || i> GetLength()) throw"位置错误";
    Node * p = rear->next;
    int j = 1;
    while(j1){
        p = p->next;
        j++;
    }
    Node* s = p->next;
    p->next = s->next;
    if(s == rear){
        rear = p;
    }
    T x = s->data;
    return x;
    
}
template <class T>
void CLinkList:: PrintList(){
    Node  *p = rear->next;
    if(p->next == rear) {cout<< "链表为空列表!"<return; }
    cout<<"按顺序单链表的各个数据元素是:"<<endl;
    while(p!=rear){
        cout<data<<" ";
        p= p->next;
    }
    cout << endl;

}
template <class T>
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 */

 

转载于:https://www.cnblogs.com/ycbeginner/p/10006351.html

你可能感兴趣的:(C++ 循环链表基本算法)