链表的并集
当有两个集合A,B求两个集合的并集
如: A = { 1, 2, 3 ,4}
B = { 3, 4, 5, 6}
A U B = { 1 ,2 ,3 ,4 ,5 ,6 };
结构体的创建,空链表创建
//定义结构体
struct Node;
typedef struct Node *Position;
struct Node
{
int num;
Position next;
};
//构建空的结构体
void Creat(Position &node)
{
node = (Position)malloc(sizeof(struct Node));
if (node == NULL)
exit(0);
node->next = NULL;
}
用定义Find函数来确保一个集合中没有重复的元素出现
int Find(Position node, int find)
{
Position P = NULL;
P = node;
while (P != NULL && P->num != find)
P = P->next;
if(P != NULL)
return P->num;
return 0;
}
//插入新的数
void Inset(Position &node, int inset)
{
if (node == NULL)
Creat(node);
//判断插入的数是否是不重复
if (Find(node, inset) == 0)
{
Position P;
P = (Position)malloc(sizeof(struct Node));
if (P == NULL)
exit(0);
P->num = inset;
P->next = node->next;
node->next = P;
}
}
接下来就需要将两个集合合并成一个集合
//将两个集合合成一个集合,写入新的链表中
Position ReCreat(Position H, Position L)
{
Position R = NULL;
//先确保两个链表都不指向最后NULL
while (H != NULL && L != NULL)
if (H->num > L->num)
{
Inset(R, H->num);
H = H->next;
}
else if (H->num < L->num)
{
Inset(R, L->num);
L = L->next;
}
//出现相同元素时
else
{
Inset(R, H->num);
H = H->next;
L = L->next;
}
//如果一个链表还没有复制完,在进行复制
while (L != NULL)
{
Inset(R, L->num);
L = L->next;
}
while(H != NULL)
{
Inset(R, H->num);
H = H->next;
}
return R;
}
源代码
#include <stdlib.h>
#include <stdio.h>
//定义结构体
struct Node;
typedef struct Node *Position;
struct Node
{
int num;
Position next;
};
//构建空的结构体
void Creat(Position &node)
{
node = (Position)malloc(sizeof(struct Node));
if (node == NULL)
exit(0);
node->next = NULL;
}
int Find(Position node, int find)
{
Position P = NULL;
P = node;
while (P != NULL && P->num != find)
P = P->next;
if(P != NULL)
return P->num;
return 0;
}
//插入新的数
void Inset(Position &node, int inset)
{
if (node == NULL)
Creat(node);
//判断插入的数是否是不重复
if (Find(node, inset) == 0)
{
Position P;
P = (Position)malloc(sizeof(struct Node));
if (P == NULL)
exit(0);
P->num = inset;
P->next = node->next;
node->next = P;
}
}
//将两个集合合成一个集合,写入新的链表中
Position ReCreat(Position H, Position L)
{
Position R = NULL;
//先确保两个链表都不指向最后NULL
while (H != NULL && L != NULL)
if (H->num > L->num)
{
Inset(R, H->num);
H = H->next;
}
else if (H->num < L->num)
{
Inset(R, L->num);
L = L->next;
}
//出现相同元素时
else
{
Inset(R, H->num);
H = H->next;
L = L->next;
}
//如果一个链表还没有复制完,在进行复制
while (L != NULL)
{
Inset(R, L->num);
L = L->next;
}
while(H != NULL)
{
Inset(R, H->num);
H = H->next;
}
return R;
}
int main()
{
Position H, L;
H = NULL, L = NULL;
int i, num;
for (i = 0; i < 4; i++)
{
scanf("%d", &num);
Inset(H, num);
}
for (i = 0; i < 4; i++)
{
scanf("%d", &num);
Inset(L, num);
}
Position R = ReCreat(H->next, L->next);
R = R->next;
while (R)
{
printf("%d ", R->num);
R = R->next;
}
system("pause");
return 0;
}