循环链表

#include<iostream>
#include<malloc.h>
#include<string.h>
#include<stdio.h>
using namespace std;
#define maxsize 100
typedef struct node
{
int data;
struct node *next;
}lnode,*linklist;

linklist link(linklist head1,linklist head2)
{
lnode *p,*q;
p=head1->next; q=head2->next;
while(p->next!=head1)
{
p=p->next;
}
while(q->next!=head2)
{
q=q->next;
}
p->next=head2->next;
q->next=head1;
return head1;
}
linklist creat(int n)
{
linklist head=(linklist)malloc(sizeof(lnode));

lnode *p,*q;
int e;
q=head;
for(int i=0;i<n;i++)
{
p=(linklist)malloc(sizeof(lnode));
cin>>e;
p->data=e;
q->next=p;//注意 别写成head 那样的话就变成了一对多关系
p->next=NULL;
q=p;
}
if(q!=NULL)
{
q->next=head;
}
return head;
// while(i<n)
// {
// cout<<"请输入第%d个元素。"<<i<<endl;
// cin>>e;
// if(i==1)
// {
// head=(linklist)malloc(sizeof(lnode));
// head->data=e;
// head->next=NULL;
// q=head;
// }
// }
}

void dis(lnode * head)
{
lnode *p,*q;
p=head;
if(p==NULL)
{
cout<<"循环链表为空!";
}
else
{
while(p->next!=head)
{ p=p->next;
cout<<p->data<<" ";
}
}
}
int main()
{
linklist h1,h2;
int n1,n2;
cout<<" 创建h1循环单链表:"<<endl;
cout<<" 请输入元素个数:"<<endl;
cin>>n1;
h1=creat(n1);

cout<<" 创建h2循环单链表:"<<endl;
cout<<" 请输入元素个数:"<<endl;
cin>>n2;
h2=creat(n2);

cout<<"输出循环单链表h1!"<<endl;
dis(h1); cout<<endl;
cout<<"输出循环单链表h2!"<<endl;
dis(h2); cout<<endl;

h1=link(h1,h2) ;
cout<<"输出合并后的循环单链表h1+h2!"<<endl;
dis(h1);
}

原文地址:https://www.cnblogs.com/mykonons/p/6591902.html