C语言已知单链表LA=(a1,a2,…,am)和LB=(b1,b2,…,bn),编写程序按以下规则将它们合并成一个单链表LC,
LC=(a1,b1,…,am,bm,bm+1,…,bn),m<=n
或者
LC=(a1,b1,…,bn,an,an+1,…,am),m>n
/*
开发者:慢蜗牛 开发时间:2020.6.11
程序功能:合并链表
*/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(struct L)
void print(struct L* head);
void insert(struct L* p1, struct L* p2);
struct L//创建结构体
{
int a;
struct L* next;
};
int n;
struct L* creat()//建立链表
{
struct L* head;
struct L* p1, * p2;
n = 0;
p1 = p2 = (struct L*)malloc(LEN);
scanf_s("%d", &p1->a);
head = NULL;
while (p1->a != -1)
{
n = n + 1;
if (n == 1) head = p1;
else p2->next = p1;
p2 = p1;
p1 = (struct L*)malloc(LEN);
scanf_s("%d", &p1->a);
}
p2->next = NULL;
return(head);
}
void print(struct L* head)//输出具有头结点的列表
{
struct L* p;
p = head->next;
if (head != NULL)
do
{
printf("--%d ", p->a);
p = p->next;
} while (p != NULL);
}
void insert(struct L* p1, struct L* p2)//从小到大合并递增链表
{
struct L* LC, * r;
LC = (struct L*)malloc(LEN);
LC->next = p1;
r = LC;
while (p1 && p2)
{
if (p1->a <= p2->a)
{
r->next = p1;
r = p1;
p1 = p1->next;
}
else
{
r->next = p2;
r = p2;
p2 = p2->next;
}
}
if (p1 == NULL) r->next = p2;
else r->next = p1;
print(LC);
}
void main()//主函数
{
struct L* LA, * LB;
printf("请输入LA的数据:");
LA = creat();
printf("请输入LB的数据:");
LB = creat();
printf("LC=");
insert(LA, LB);
}