#include <bits/stdc++.h>
using namespace std;
int flag=0;
template<typename T>
struct LinkNode{
T data;
LinkNode<T> *next;
LinkNode():next(NULL){};
LinkNode(T d):data(d),next(NULL){};
};
template<typename T>
class LinkListClass{
public:
LinkNode<T> *head=new LinkNode<T>;
void CreateListF(T x[],int l){
for(int i=0;i<l;i++){
LinkNode<T> *p=new LinkNode<T>(x[i]);
p->next=head->next;
head->next=p;
}
}
void CreateListR(T y[],int l){
LinkNode<T> *q;
q=head;
for(int i=0;i<l;i++){
LinkNode<T> *p=new LinkNode<T>(y[i]);
q->next=p;
q=p;
}
}
int ListLength(){
int count=0;
LinkNode<T> *p=new LinkNode<T>;
p=head->next;
while(p!=NULL){
count++;
p=p->next;
}
return count;
}
void DispList(){
LinkNode<T> *p=new LinkNode<T>;
p=head->next;
while(p!=NULL){
cout<<p->data<<‘ ‘;
p=p->next;
}
cout<<endl;
}
int GetElem(T x,int result){
LinkNode<T> *p=new LinkNode<T>;
p=head->next;
while(p->data!=x&&p!=NULL){
p=p->next;
}
if(p==NULL) return 0;
return 1;
}
int LocateElem(T x){
LinkNode<T> *p=new LinkNode<T>;
p=head->next;
int i=0;
while(p!=NULL){
if(p->data==x) return i;
p=p->next;
i++;
}
return -1;
}
bool ListInsert(int pos,T x){
int i=0;
LinkNode<T> *p;
p=head->next;
if(p==NULL){
p=new LinkNode<T>(x);
head->next=p;
if(x) flag=1;
return true;
}
if(flag) i+=1;
while(p!=NULL){
if(i==pos-1){
LinkNode<T> *q=new LinkNode<T>(x);
q->next=p->next;
p->next=q;
return true;
}
p=p->next;
i++;
}
return false;
}
bool ListDelete(int pos){
int i=0;
LinkNode<T> *p=new LinkNode<T>;
p=head->next;
while(p!=NULL){
if(i==pos-1){
delete p->next;
p->next=NULL;
return true;
}
p=p->next;
i++;
}
return false;
}
void Reverse(){
LinkNode<T> *p;
p=head->next;
head->next=NULL;
while(p!=NULL){
LinkNode<T> *q=p;
p=p->next;
q->next=head->next;
head->next=q;
}
}
};
int main(){
LinkListClass<int> a,b;
int x[]={1,2,3};
int y[]={4,5,6,7};
a.CreateListF(x,3);
cout<<a.ListLength()<<“: “;
a.DispList();
b.CreateListR(y,4);
cout<<b.ListLength()<<“: “;
b.DispList();
int result=1;
if(a.GetElem(1,result)) cout<<result<<endl;
cout<<b.LocateElem(6)<<endl;
if(a.ListInsert(1,5)) a.DispList();
if(a.ListDelete(3)) a.DispList();
LinkListClass<int> A;
int z[]={1,2,3,4};
A.CreateListR(z,4);
A.DispList();
A.Reverse();
A.DispList();
int i,j;
LinkListClass<int> c;
for(i=1;i<=10;i++) c.ListInsert(i,i);
c.DispList();
c.Reverse();
c.DispList();
return 0;
}
本文为原创文章,转载请注明出处!
admin:支持一下,感谢分享!,+10,