循环链表即单链表的改良,将单链表的尾结点的指针NULL改为指向头结点的地址,从而达到循环的作用;
将尾结点的地址标记为rear,那么头结点的地址就是rear->next,第一结点就是rear->next->next
/*循环链表必须采用尾插法来整体建表,负责很复杂*/
#include<iostream>
#include<windows.h>
#include<time.h>
using namespace std;
typedef struct student{
int data;
struct student *next;
}student;
typedef struct student *list;
list creatlist(list *L,int n)
{
list p,s;
int elem;
(*L)=new student;
p=(*L);
p->next=p;
for(int i=1;i<=n;i++)
{
s=new student;
elem=rand()%100+1;
s->data=elem;
s->next=p->next;
p->next=s;
p=s;
}
return s;
}
int show(list L,list rear)
{
list p;
p=L->next;
while(p!=rear->next)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int Connect(list &rearA,list &rearB)
{
list p,q;
p=rearA->next; //**不能省略,否则出错
rearA->next=rearB->next->next;
q=rearB->next;
rearB->next=p;
delete(q);
}
int main()
{
list A,B; //链表A和B
list rearA,rearB; //链表A和B的尾指针
srand(time(NULL));
int n=10;
rearA=creatlist(&A,n);
show(A,rearA);
rearB=creatlist(&B,n);
show(B,rearB);
Connect(rearA,rearB); //连接A,B俩个链表
show(A,rearB);
}