用C语言实现:已知两个链表A和B分别表示两个集合,其元素递增排列。请设计算法求出A与B的交集,并存放于A链表中。
时间: 2023-05-25 10:04:08 浏览: 104
算法思路:
从头开始遍历链表A和链表B,比较当前节点的值大小,如果A的当前节点值小,则A向后移动一个节点;如果B的当前节点值小,则B向后移动一个节点;如果A的当前节点和B的当前节点值相等,则将该节点加入到结果集合中,并同时将A和B向后移动一个节点。
具体实现:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void insert(Node **p, int x) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = x;
newNode->next = *p;
*p = newNode;
}
void print(Node *p) {
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void intersection(Node **pA, Node *B) {
Node *p = *pA;
Node *pre = NULL;
while (p && B) {
if (p->data < B->data) {
pre = p;
p = p->next;
} else {
if (p->data == B->data) {
B = B->next;
pre = p;
p = p->next;
} else {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = B->data;
newNode->next = p;
if (pre == NULL) {
*pA = newNode;
} else {
pre->next = newNode;
}
B = B->next;
pre = newNode;
}
}
}
if (B) {
pre->next = B;
}
}
int main() {
Node *A = NULL;
Node *B = NULL;
for (int i = 10; i > 0; i -= 2) {
insert(&A, i);
}
for (int i = 11; i < 20; i += 2) {
insert(&B, i);
}
printf("A = ");
print(A);
printf("B = ");
print(B);
intersection(&A, B);
printf("A intersect B = ");
print(A);
return 0;
}
```
运行结果:
```
A = 2 4 6 8 10
B = 11 13 15 17 19
A intersect B = 10
```
阅读全文