# include<iostream>
# include<stdlib.h>
# include<stdio.h>
# include<iomanip>
# include<cstring>
using namespace std;
typedef struct
{
int num; //学号
char name[10]; //姓名
}student;
typedef student etype;
typedef struct chainnode
{
etype data;
chainnode *plink;
chainnode *nlink;
}chainnode;
typedef struct
{
chainnode *first;
}headnode;
typedef headnode *chainlist;
chainlist L;
void creat(chainlist &L)
{
L=new headnode;
L->first=NULL;
}
void output(chainlist &L)
{
chainnode *p=L->first;
if(p==NULL)
cout<<"这是一个空链表"<<endl;
else
{
while(p)
{
cout<<p->data.name<<'\t'<<p->data.num<<endl;
p=p->nlink;
}
}
cout<<endl;
}
bool insert(chainlist &L,int k,etype x) //插入到第k个位置
{
chainnode *p=L->first;
int index=1;
if(k<0)
return false;
while(index<k&&p)
{
p=p->nlink;
index++;
}
if(!p&&k>0) //不存在第k个元素
return false;
chainnode *q=new chainnode;
q->data=x;
if(k==0)
{
q->nlink=p;
q->plink=NULL;
p->plink=q;
}
else
{
q->nlink=p->nlink;
q->plink=p;
chainnode *j=p->nlink;
if(p)
j->plink=q;
p->nlink=q;
}
}
bool delet(chainlist &L,int k) //删除第k个元素
{
int t=1;
if(k<1)
return false;
chainnode *p=L->first;
while(t<k-1&&p!=NULL)
{
p=p->nlink;
t++;
}
if(k==1)
{
chainnode *q=p->nlink;
L->first=q;
q->plink=NULL;
delete p;
return true;
}
else
{
if(p->nlink==NULL)
return false;
else
{
chainnode *q=p->nlink;
chainnode *j=q->nlink;
p->nlink=j;
if(j==NULL)
q->plink=NULL;
else
j->plink=p;
delete q;
}
}
}
void find(chainlist &L,int id)
{
chainnode *p=L->first;
int flag=0;
while(p&&flag==0)
{
if(p->data.num==id)
{
flag=1;
break;
}
p=p->nlink;
}
if(flag==0)
cout<<"没有找到学生!"<<endl;
else
{
cout<<"该学生的基本信息如下:"<<endl;
cout<<"姓名:"<<p->data.name<<'\t'<<"学号:"<<p->data.num<<endl;
}
}
void findbeforeandafter(chainlist &L,int id,int x,int y)
{
chainnode *current=L->first;
int j=1;
while(current&¤t->data.num!=id)
{
j++;
current=current->nlink;
}
if(!current)
cout<<"未找到有该学号的同学:"<<endl;
else
{
chainnode *p=current;
chainnode *q=current;
for(int i=j;i>j-x&&p;i--)
p=p->plink;
if(!p)
{
cout<<"上述同学不存在第"<<x<<"个前驱同学"<<endl;
}
else
{
cout<<"已成功找到上述同学的第"<<x<<"个前驱同学"<<endl;
cout<<"该同学的信息如下:"<<endl;
cout<<"姓名:"<<p->data.name<<'\t'<<"学号:"<<p->data.num<<endl;
cout<<endl;
}
for(int a=j;a<j+y;a++)
q=q->nlink;
if(!q)
cout<<"上述同学不存在第"<<y<<"个后驱同学"<<endl;
else
{
cout<<"已成功找到上述同学的第"<<y<<"个后驱同学"<<endl;
cout<<"该同学的信息如下:"<<endl;
cout<<"姓名:"<<q->data.name<<'\t'<<"学号:"<<q->data.num<<endl;
cout<<endl;
}
}
}
int main()
{ creat(L);
int num;
char name[10];
cout << "请输入学生信息(学号 姓名),输入0结束:" << endl;
while (1)
{
cin >> num;
if (num == 0) break;
student stu;
cin>>stu.name;
stu.num=num;
int k;
cout << "请输入要插入的位置:";
cin >> k;
insert(L, k, stu);
}
output(L);
return 0;
}