1 #include 2 using namespace std; 3 template 4 struct Node 5 { 6 T data; 7 Node *next; 8 }; 9 template 10 class LinkList 11 { 12 public: 13 LinkList(); 14 LinkList(T a[],int n); 15 ~LinkList(); 16 int length(); 17 T Get(int i); 18 void Insert(int i,T x); 19 void Delete(int i); 20 void PrintList(); 21 int Locate(T x); 22 private:Node *first;//单链表的头指针; 23 }; 24 template 25 LinkList ::LinkList()//无参构造函数 26 { 27 first=new Node ; 28 first=NULL; 29 } 30 /*template 31 LinkList ::LinkList(T a[],int n)//头插法 32 { 33 first=new Node ; 34 first->next=NULL; 35 36 for( int i=0;i *s; 39 s=new Node ; 40 s->data=a[i]; 41 s->next=first->next; 42 first->next=s; 43 44 } 45 }*/ 46 template 47 LinkList ::LinkList(T a[],int n)//尾插法 48 { 49 first=new Node ; 50 first->next=NULL; 51 52 Node *p; 53 p=first; 54 55 for( int i=0;i *s=new Node ; 58 59 s->data=a[i]; 60 61 s->next=p->next; 62 63 p->next=s; 64 65 p=p->next; 66 67 } 68 } 69 70 template 71 LinkList ::~LinkList() 72 { 73 Node *q=new Node ; 74 while(first!=NULL) 75 { 76 q=first; 77 first=first->next; 78 delete q; 79 } 80 } 81 template 82 void LinkList ::PrintList() 83 { 84 Node *current; 85 current=first->next; 86 while(current!=NULL) //遍历操作; 87 { 88 cout< data<<" "; 89 current=current->next; 90 } 91 cout< 95 int LinkList ::length() 96 { 97 Node *p; 98 p=first->next; 99 int count=0; 100 while(p!=NULL) 101 { 102 p=p->next; 103 count++; 104 } 105 return count; 106 } 107 template 108 T LinkList ::Get(int i) 109 { 110 Node *p; 111 p=first->next; 112 int count =1; 113 while(count next; 116 117 count++; 118 119 } 120 if(p==NULL) 121 cout<<"位置输入错误"< data; 124 125 } 126 template 127 void LinkList ::Delete(int i) 128 { 129 Node *p; 130 p=first; 131 int count=0; 132 while(p!=NULL&&count next; 135 count++; 136 } 137 if(p==NULL||i<0) 138 { 139 cout<<"输入错误"< *q; 144 q=p->next; 145 p->next=q->next; 146 delete q; 147 } 148 } 149 template 150 void LinkList ::Insert(int i,T x) 151 { 152 Node *p; 153 p=first; 154 int count=0; 155 while(count next; 158 count++; 159 } 160 if(i<0||p==NULL) 161 { 162 cout<<"输入错误"< *s; 166 s=new Node ; 167 s->data=x; 168 s->next=p->next; 169 p->next=s; 170 } 171 } 172 template 173 int LinkList ::Locate(T x) 174 { 175 Node *p; 176 p=first->next; 177 int count =1; 178 while(p!=NULL) 179 { 180 p=p->next; 181 182 count++; 183 if (p->data==x) 184 { 185 break; 186 } 187 } 188 if(p==NULL) 189 cout<<"位置输入错误"<
c(a,10); 199 cout<<"打印链表:"; 200 c.PrintList(); 201 202 cout<<"输出位置2的元素:"<