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