#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data ;
struct node *next ;
} node ;
node *create (node *head); // 创建循环链表
void display (node *tail); // 打印循环链表
node *combine (node *left , node *right); // 合并循环链表
int main ()
{
node *list1 = NULL ;
node *list2 = NULL ;
node *list3 = NULL ;
printf("请录入两个循环链表:\n");
list1 = create(list1) ;
list2 = create(list2) ;
display(list1);
display(list2);
printf("合并两个循环链表:\n");
list3 = combine(list1 , list2);
display(list3);
return 0 ;
}
node *create (node *head)
{
node *target = NULL ;
node *tail = NULL ;
int input = 1 ;
while (1)
{
scanf("%d",&input);
if (input == 0)
{
return tail ; // 返回尾结点
}
else
{
if (head == NULL) // 第一次插入结点
{
head = (node *)malloc(sizeof(node)); // 动态分配内存
head->next = head ; // 形成闭合循环链表
head->data = -1 ; // 头结点不存数据,-1代表不存数据
tail = head ; // 既是头结点,也是尾结点
}
for (target = head ; target->next != head ; target = target->next); // 找到当前尾结点
tail = (node *)malloc(sizeof(node));
tail->data = input ;
target->next = tail ; // 将当前的尾结点指向新的结点
tail->next = head ; // 再用新的结点指向头结点,成为新的尾结点
}
}
}
void display (node *tail)
{
node *target = NULL ;
while (1)
{
for (target = tail->next ; target->next != tail->next ; target = target->next)
// 打印除了尾结点外的全部结点
{
printf("%d ",target->data);
}
printf("%d\n",target->data); // 打印尾结点
return ;
}
}
node *combine (node *left , node *right)
{
node *tmp = left->next ; // 录入第一链表的头结点
left->next = right->next->next ;
// right->next 就是第一链表的头结点,但不存数据,所以还要再步进找到存储数据的第一个结点
free(right->next); // 释放第二链表的头结点
right->next = tmp ; // 第二链表的尾结点接上第一链表的头结点,形成闭环
return right ; // 返回整条链表的尾结点
}