#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
//定义一个结构体student
typedef struct
{
int age;
char name[10];
int number;
}student;
typedef student Etype;
//用结构体定义结点的数据类型
struct chainnode
{
Etype data;
struct chainnode *link;
};
typedef struct
{ chainnode *first;
int length;
}chainhead;
//初始化链表为空链表
chainhead * L;
chainhead * Creat(chainhead *L)
{
L->first=NULL;
return L;
};
//实现单链表元素的后插操作
bool chainInsert(chainhead *L,int i,Etype &e)
{ if(i<1)
return false;
if(i==1)
{
chainnode *q=new chainnode;
q->data=e;
q->link=L->first;
L->first=q;
}
chainnode *p=L->first;
int j=1;
while(p!=NULL&&j<i-1)//循环找到第i-1个结点
{
j++;
p=p->link ;
}
if(p==NULL)
return false;//i值不合法
chainnode *q=new chainnode;
q->data=e;
q->link=p->link ;
p->link =q;
return true;
};
//按位查询并返回结点
chainnode *Getelement(chainhead * L,int i)
{
int j=1;
chainnode *p=L->first ;
if(i<=0)
return NULL;
while(p!=NULL&&j<i)
{
j++;
p=p->link;
}
return p;
};
//按位删除结点
bool chainDelete(chainhead * L,int k)
{ if(k<1||L->first ==NULL)
return false;
chainnode *p=L->first ;
if(k==1)
{
L->first =p->link ;
return true;
}
int j=1;
while(p!=NULL&&j<k-1)
{ p=p->link ;
j++;
}
if(p==NULL||p->link ==NULL)
return false;
chainnode *s=p->link;
p->link =s->link ;
delete s;
return true;
};
//按值查找结点
chainnode *Locateelement(chainhead *L,int a)
{ chainnode *p=L->first ;
while(p!=NULL&& p->data.number !=a)
p=p->link ;
if(p==NULL)
{ cout<<"没有查询到结果"<<endl;
return NULL;
}
else
return p;
};
//删除单链表
void Destroy(chainhead *L)
{ chainnode *current=L->first ;
while(L->first )
{
current=current->link ;
delete L->first ;
L->first =current;
}
delete L;
};
void CSH(Etype Student[10])
{
int number[10]={1,2,3,4,5,6,7,8,9,10};
int age[10]={18,18,18,18,18,18,18,18,18,18};
char name[10][10]={"李白","杜甫","白居易","欧阳修","苏轼","曾巩","苏洵","苏辙","王安石","张九龄"};
for(int i=0;i<10;i++)
{
strcpy(Student[i].name,name[i]);
Student[i].number=number[i];
Student[i].age=age[i];
}
};
//设置新同学信息
void Insertelement(Etype &e)
{ cout<<"请输入新同学的姓名 :"<<endl;
cin>>e.name ;
cout<<"请输入新同学的学号 :"<<endl;
cin>>e.number ;
cout<<"请输入新同学的年龄 :"<<endl;
cin>>e.age ;
};
int count(int length)
{
chainnode *current=L->first ;
while(current)
length++;
return length;
};
int main()
{
Creat(L);
Etype Student[10];
Etype e;
CSH(Student);
for(int i=0;i<10;i++)
chainInsert(L,i,Student[i]);
Insertelement(e);
cout<<"请输入想要插入的位置"<<endl;
int k;
cin>>k;
chainInsert(L,k,e);
cout<<"请输入想要查询的学生的学号:"<<endl;
int a;
cin>>a;
cout<<"该学生的信息如下 :"<<endl;
cout<<Locateelement(L,a);
cout<<"输入你想找到的同学的位序 :"<<endl;
int b;
cin>>b;
cout<<"该学生的信息如下 :"<<endl;
cout<<Getelement(L,b);
cout<<"请输入想要删除的元素的位序 :"<<endl;
int c;
cin>>c;
chainDelete(L,c);
int length=1;
cout<<"链表的长度为:"<<endl;
count(length);
Destroy(L);
return 0;
};
最后的结果是这个,不知道是哪个位置不对