C语言实现:【问题描述】 假设以两个元素依值递增有序排列的线性表A和B分别表示两个集合(即同一表中的元素值各不相同),现要求另辟空间构成一个线性表C,其元素为A和B中元素的交集,且表C中的元素也依值递增有序排列。试对单链表编写求C的算法。LC为一个新建的链表。 【输入形式】 链表A长度 链表A(空格区分) 链表B长度 链表B(空格区分) 【输出形式】 链表C 【样例输入】 6 1 2 3 5 7 9 11 4 2 4 5 9 【样例输出】 2 5 9
时间: 2024-04-06 17:34:12 浏览: 90
以下是C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkList;
void CreateList(LinkList *L, int len) {
int i;
Node *p, *r;
*L = (LinkList) malloc(sizeof(Node));
r = *L;
printf("Please input %d elements: ", len);
for (i = 0; i < len; i++) {
p = (Node *) malloc(sizeof(Node));
scanf("%d", &p->data);
r->next = p;
r = p;
}
r->next = NULL;
}
void Merge(LinkList La, LinkList Lb, LinkList *Lc) {
Node *pa, *pb, *pc, *r;
pa = La->next;
pb = Lb->next;
r = *Lc = (LinkList) malloc(sizeof(Node));
while (pa && pb) {
if (pa->data < pb->data) {
pa = pa->next;
} else if (pa->data > pb->data) {
pb = pb->next;
} else {
pc = (Node *) malloc(sizeof(Node));
pc->data = pa->data;
r->next = pc;
r = pc;
pa = pa->next;
pb = pb->next;
}
}
r->next = NULL;
}
void PrintList(LinkList L) {
Node *p = L->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
}
int main() {
LinkList La, Lb, Lc;
int lena, lenb;
printf("Please input the length of List A: ");
scanf("%d", &lena);
CreateList(&La, lena);
printf("Please input the length of List B: ");
scanf("%d", &lenb);
CreateList(&Lb, lenb);
Merge(La, Lb, &Lc);
printf("The intersection of A and B is: ");
PrintList(Lc);
printf("\n");
return 0;
}
```
运行结果:
```
Please input the length of List A: 6
Please input 6 elements: 1 2 3 5 7 9
Please input the length of List B: 4
Please input 4 elements: 2 4 5 9
The intersection of A and B is: 2 5 9
```
阅读全文