编写程序,采用单链表表示集合(假设同一集合中不存在重复元素),将其按递增有序方式排列,构成有序单链表,并求这两个集合的差,C语言示例
时间: 2024-09-29 10:07:43 浏览: 49
在C语言中,我们可以使用链表结构来表示集合,并通过头插法(insertion sort)对链表进行排序。这里我将为你展示如何操作两个链表,分别表示有序集合A和B,然后计算它们的交集(即相同元素)以及差集(A中B不含的元素)。假设我们已经有一个结构体`Node`用于表示链表节点:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点定义
typedef struct Node {
int data;
struct Node* next;
} Node;
// 插入排序函数
void insert(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
if (*head != NULL && (*head)->data > value)
*head = newNode;
else {
Node* current = *head;
while (current->next != NULL && current->next->data < value)
current = current->next;
newNode->next = current->next;
current->next = newNode;
}
}
// 计算并打印集合A
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// 打印集合B
void printListB(Node* head) {
// 类似于printList,省略代码
}
int main() {
// 初始化链表和数据
Node* listA = NULL, *listB = NULL;
int A[] = {5, 3, 8, 4, 2};
int B[] = {6, 3, 7, 9};
// 遍历数组A,插入到listA
for (int i = 0; i < sizeof(A)/sizeof(A[0]); i++)
insert(&listA, A[i]);
// 遍历数组B,插入到listB
for (int i = 0; i < sizeof(B)/sizeof(B[0]); i++)
insert(&listB, B[i]);
// 求A和B的交集
Node* intersection = NULL;
for (Node* a = listA, *b = listB; a != NULL && b != NULL; ) {
if (a->data == b->data) {
intersection = (intersection == NULL) ? a : intersection;
a = a->next;
b = b->next;
} else if (a->data < b->data)
a = a->next;
else
b = b->next;
}
printf("Sorted List A: ");
printList(listA);
printf("Sorted List B: ");
printListB(listB);
if (intersection != NULL)
printf("Intersection: ");
else
printf("No intersection.\n");
// 输出差集
printf("Difference of A and B: ");
Node* diffA = listA;
while (diffA != NULL) {
if (diffA != intersection) {
printf("%d ", diffA->data);
if (diffA->next == intersection) break; // 差集结束
}
diffA = diffA->next;
}
return 0;
}
```
阅读全文