已知两个顺序表A和B分别表示两个集合,其元素递增排列,编写一个函数求出A和B的交集C,要求C同样以元素递增的顺序表形式存储。用c语言写出此算法
时间: 2024-10-10 15:12:55 浏览: 59
在C语言中,我们可以使用双指针法来解决这个问题。以下是算法步骤:
1. 初始化两个指针i和j,分别指向A和B的头部。
2. 当两个指针都有效(即i和j都没有越界)时,做以下操作:
a. 检查当前A[i]是否小于或等于B[j]。如果是,将A[i]加入结果集C,并移动指针i向前一位。
b. 如果不是,则移动B[j]向前一位,因为我们要找的是A和B中的公共元素。
3. 当其中一个列表遍历完时,另一个列表剩下的部分就不可能包含已遍历过的元素,所以停止循环。
下面是C语言的具体实现:
```c
#include <stdio.h>
// 结构体表示有序表节点
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
newNode->data = value;
newNode->next = NULL;
}
return newNode;
}
// 插入有序表中
void insert(Node** head, int value) {
Node* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next && current->next->data < value) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
// 找到并添加交集
void findIntersection(Node* listA, Node* listB, Node** result) {
Node* resultHead = NULL;
Node* i = listA, *j = listB;
while (i && j) {
if (i->data <= j->data) {
if (resultHead == NULL) {
resultHead = i;
} else {
Node* lastNode = resultHead;
while (lastNode->next && lastNode->next->data < i->data) {
lastNode = lastNode->next;
}
lastNode->next = i;
}
i = i->next;
} else {
j = j->next;
}
}
*result = resultHead;
}
// 打印链表
void printList(Node* head) {
while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
// 假设A和B已经初始化
Node* listA = ...; // 有序表A的头结点
Node* listB = ...; // 有序表B的头结点
Node* intersection = NULL;
findIntersection(listA, listB, &intersection);
printf("交集C(递增顺序): ");
printList(intersection);
return 0;
}
```
阅读全文