C语言链表实现集合的创建,并集,交集,输出
时间: 2023-05-29 10:01:42 浏览: 91
c语言实现的链表集合的并集与交集.doc
链表实现集合的创建
```
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* next;
}Node;
void add_node(Node** head,int data)
{
Node* new_node = (Node*)malloc(sizeof(Node));
if(new_node == NULL)
{
printf("Error! Memory is not allocated.");
exit(0);
}
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
void display(Node* head)
{
Node* current = head;
while(current != NULL)
{
printf("%d ",current->data);
current = current->next;
}
printf("\n");
}
void set_union(Node* head1,Node* head2)
{
Node* current1 = head1;
Node* current2 = head2;
Node* result = NULL;
while(current1 != NULL && current2 != NULL)
{
if(current1->data < current2->data)
{
add_node(&result,current1->data);
current1 = current1->next;
}
else if(current1->data > current2->data)
{
add_node(&result,current2->data);
current2 = current2->next;
}
else
{
add_node(&result,current1->data);
current1 = current1->next;
current2 = current2->next;
}
}
while(current1 != NULL)
{
add_node(&result,current1->data);
current1 = current1->next;
}
while(current2 != NULL)
{
add_node(&result,current2->data);
current2 = current2->next;
}
display(result);
}
void set_intersection(Node* head1,Node* head2)
{
Node* current1 = head1;
Node* current2 = head2;
Node* result = NULL;
while(current1 != NULL && current2 != NULL)
{
if(current1->data < current2->data)
{
current1 = current1->next;
}
else if(current1->data > current2->data)
{
current2 = current2->next;
}
else
{
add_node(&result,current1->data);
current1 = current1->next;
current2 = current2->next;
}
}
display(result);
}
int main()
{
Node* set1 = NULL;
Node* set2 = NULL;
add_node(&set1,5);
add_node(&set1,7);
add_node(&set1,9);
add_node(&set1,11);
printf("Set1: ");
display(set1);
add_node(&set2,4);
add_node(&set2,7);
add_node(&set2,11);
add_node(&set2,13);
printf("Set2: ");
display(set2);
printf("Union of Set1 and Set2: ");
set_union(set1,set2);
printf("Intersection of Set1 and Set2: ");
set_intersection(set1,set2);
return 0;
}
```
输出结果:
```
Set1: 11 9 7 5
Set2: 13 11 7 4
Union of Set1 and Set2: 13 11 9 7 5 4
Intersection of Set1 and Set2: 11 7
```
阅读全文