文章目录1.两个有序单链表的交集2.两个有序单链表的并集
单链表的实现:https://blog..net/weixin_41892460/article/details/82855823
1.两个有序单链表的交集
void UnionSetJ(pList list1, pList list2)
{
if (list1 == NULL || list2 == NULL)
return;
while (list1 && list2)
{
if (list1->data < list2->data)
{
list1 = list1->next;
}
else if (list1->data > list2->data)
{
list2 = list2->next;
}
else
{
printf("%d ", list1->data);
list1 = list1->next;
list2 = list2->next;
}
}
}
2.两个有序单链表的并集
void UnionSetC(pList list1, pList list2)
{
pList prev1 = NULL;
pList prev2 = NULL;
if (list1 == NULL || list2 == NULL)
return;
while (list1 && list2)
{
if (list1->data == list2->data)
{
list1 = list1->next;
list2 = list2->next;
printf("%d\n",list1->data);
}
else if (list1->data > list2->data)
{
prev2 = list2;
list2 = list2->next;
printf("%d ", prev2->data);
}
else
{
prev1 = list1;
list1 = list1->next;
printf("%d ", prev1->data);
}
}
while (list1)
{
printf("%d ", list1->data);
list1 = list1->next;
}
while (list2)
{
printf("%d ", list2->data);
list2 = list2->next;
}
}