以下是某同学的成绩,通过双链表实现增加,删除,查询等功能。
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* next,*prior;
};
class List{
public:
List();
List(int a[],int n);
~List();
int length();
int Get(int i);
int Locate(int x);
void Insert(int i,int x);
int Delete(int i);
void Print();
private:
Node*first;
};
List::List(){
first=new Node;
first->next=NULL;
first->prior=NULL;
}
List::List(int a[],int n){ //头插法新建链表
Node*s;
int i;
first=new Node;
first->next=NULL;
for(i=0;i<n;i++)
{
s=new Node;
s->data=a[i];
s->next=first->next;
first->next=s;
}
}
void List::Print(){ //遍历链表
Node*p;
p=first->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
int List::length(){ //求表长
Node*p; int count;
p=first->next;
count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
return count;
}
int List::Get(int i){ //按位查找
Node*p;int count;
p=first->next;
count=1;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL) throw"位置";
else return p->data;
}
int List::Locate(int x){ //按值查找
Node*p;int count;
p=first->next;
count=1;
while(p!=NULL)
{
if(p->data==x) return count;
p=p->next;
count++;
}
return 0;
}
void List::Insert(int i,int x){ //插入
Node*p,*s;int count;
p=first;
count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL) throw"位置";
else{
s=new Node;
s->data=x;
s->next=p->next;
p->next=s;
}
}
int List::Delete(int i) //删除
{
Node *q,*p; int x;
p=first;
p = first;
while (i-- > 1) //因为p是从first开始走,走一次i减一次。但最后是要在i前面的,所以大于一
p= p->next;
if(p==NULL||p->next==NULL) throw"位置";
else{
q = p->next;
x=q->data;
if (p->next != NULL){
if(q->next!=NULL)
q->next->prior = p;
else{
p->next=NULL;
p->next = q->next;
delete q;
q = NULL;
return x;
}
}
p->next = q->next;
delete q;
q = NULL;
return x;
}}
List::~List() //析构
{
Node*q;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
int main()
{
int n,i,p,num,numb,se,x,a[100];
cout<<"请输入需要创建双链表的结点个数:"<<endl;
cin>>n;
cout<<"请输入需要创建双链表的结点:"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
List student(a,n);
cout<<"打印链表值如下:"<<endl;
student.Print();
cout<<endl<<"请输入插入结点的位置和值;"<<endl; cin>>p>>num;
student.Insert(p,num);
cout<<"打印链表值如下:";
student.Print();
cout<<endl<<endl<<"请输入要删除结点的位置:"<<endl; cin>>numb;
cout<<"it's "<<student.Delete(numb)<<endl<<"打印链表值如下:"<<endl;
student.Print();
cout<<endl<<endl<<"请输入要查找结点的位置:"<<endl; cin>>se;
cout<<"打印链表值如下:"<<student.Get(se)<<endl;
cout<<endl<<endl<<"请输入要查找结点的数值:"<<endl; cin>>x;
cout<<"它的位置是:"<<student.Locate(x)<<endl;
return 0;
}
实验结果如图所示: