实验二单链表

来源:互联网 发布:网络摄像机管理软件 编辑:程序博客网 时间:2024/04/29 20:02
#include<iostream>using namespace std;template<class T>struct Node{    T data;Node<T>*next;};template<class T>class Linklist{public:Linklist();Linklist(T a[],int n);~Linklist();void Insert(int i,T x);int Locate(T x);T Delete(int i);void Printlist();private:Node<T>*first;};template<class T>Linklist<T>::Linklist(){first=new Node<T>;first->next=NULL;}template<class T>Linklist<T>::Linklist(T a[],int n){Node<T> *r,*s;first=new Node<T>;r=first;for(int i=0;i<n;i++){s = new Node<T>;          s->data=a[i];          r->next =s;          r=s;  }  r->next= NULL;  }  template<class T>Linklist<T>::~Linklist(){Node<T> *q = NULL;  while(first != NULL)  {  q = first;  first= first->next;  delete q;  }  }  template<class T>void Linklist<T>::Insert(int i,T x){Node<T>*p=first,*s=NULL;int count = 0;      while(p!=NULL&&count< i-1)  {  p = p->next;  count++;  }  if(p==NULL) throw "位置非法";  else  {  s = new Node<T>;  s->data =x;  s->next=p->next;  p->next= s;  }  }  template<class T>T Linklist<T>::Delete(int i){Node<T> *p =first,*q=NULL;  T x;  int count = 0;  while(p!=NULL && count<i-1)  {  p = p->next;  count++;  }  if(p==NULL ||p->next==NULL) throw"位置";  else  {  q=p->next;  x=q->data;  p->next=q->next;  return x;  }  }    template<class T>int Linklist<T>::Locate(T x){  Node<T>*p =first->next;  int count =1;  while(p!=NULL)  {  if(p->data==x) return count;  p=p->next;  count++;  }  return 0;  }    template<class T>void Linklist<T>::Printlist(){  Node<T>*p =first-> next;  while(p!=NULL)  {  cout<<p->data<<" ";  p=p->next;  }  cout<<endl;  }    void main(){      int a[3] = {4, 5, 6};      Linklist<int> B(a, 3);      cout << "插入前的数据为:" << endl;      B.Printlist();  B.Insert(2,9);     cout << "插入操作后的数据为:" << endl;      B.Printlist();      cout << "值为9的元素的位置为:";      cout << B.Locate(9) << endl;      cout << "删除前的数据为:" << endl;      B.Printlist();      B.Delete(1);      cout << "删除后的数据为:" << endl;      B.Printlist();  }

0 0