/*
5
zhao
70
4
zhou
60
3
chen
50
2
huang
40
1
zhan
30
10
ye
120
9
dai
110
8
feng
100
7
liu
90
6
liang
80
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char num[8];
char name[8];
int score;
}ElemType;
typedef struct Lnode{
ElemType data;
struct Lnode *next;
}Lnode,*LinkList;
//链表的初始化:生成新结点作头结点,用头指针L指向头结点
void InitList_L(LinkList* L)//修改为二级指针
{
(*L)=(LinkList)malloc(sizeof(Lnode));
(*L)->next=NULL;//将头结点的指针域置空
}
//给循环链表输入具体数据(头插法,倒着依次输入数据)
void input(LinkList* L,int n)//修改为二级指针
{
int i,j=1;
Lnode *p;
InitList_L(L);//修改
for (i=n;i>0;--i)
{
//根据输入内容创建节点
p=(Lnode*)malloc(sizeof(Lnode));
printf("num=");
scanf("%s",&p->data.num);
printf("\nname=");
scanf("%s",&p->data.name);
printf("\nscore=");
scanf("%d",&p->data.score);
//头插法
p->next=(*L)->next;
(*L)->next=p;
}//头插法循环结束后,此时p指向首元结点
while (p->next&&j<n)
{p=p->next;++j;}//p指向最后一个结点
p->next=*L;//最后一个结点的指针域指向头结点
}
//把单链表中的所有数据输出出来
void print(LinkList L,int n)
{
int i;
Lnode *p;
p=L->next;
for (i=1;i<=n;i++)
{
printf("[%d].num=%-12s,name=%-12s,score=%d\n",i,p->data.num,p->data.name,p->data.score);
p=p->next;
}
printf("\n\n");
}
//带尾指针的循环链表的合并
void connect(LinkList* L1,LinkList* L2)
{
Lnode *p1,*p2,*p;//用于表示L1和L2的尾指针
int j=1,n=5;
p1=(*L1)->next;
p2=(*L2)->next;
while (p1->next&&j<n)
{p1=p1->next;++j;}
j=1;
while (p2->next&&j<n)
{p2=p2->next;++j;}
printf("The last member of L1 is: name=%s\n",p1->data.name);
printf("The last member of L2 is: name=%s\n",p2->data.name);
p=p1->next;//p存L1头结点
p1->next=(*L2)->next;//L2首元连接L1表尾
free(*L2);//释放L2头结点
p2->next=p;//L2尾结点连接L1头结点
}
int main()
{
LinkList L1,L2;
int n=5,j=1;
//头插法,请从后往前输入数据,建立两个循环链表
printf("Please type some messages about the first list:\n");
input(&L1,n);
print(L1,n);
printf("Please type some messages about the second list:\n");
input(&L2,n);
print(L2,n);
//带尾指针的循环链表的合并
connect(&L1,&L2);
print(L1,10);
return 0;
}
【单向循环链表】单向循环链表的合并
于 2022-07-29 20:25:52 首次发布