用C语言实现:已知两个链表A和B分别表示两个用户输入的集合,其元素递增排列。请设计算法求出A与B的交集,并存放于A链表中
时间: 2023-05-25 18:03:28 浏览: 127
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createSet();
void printSet(Node* head);
void intersect(Node* A, Node* B);
int main() {
Node* A = createSet();
Node* B = createSet();
printf("Set A: ");
printSet(A);
printf("Set B: ");
printSet(B);
intersect(A, B);
printf("Intersection of Set A and Set B: ");
printSet(A);
return 0;
}
Node* createSet() {
Node* head = NULL;
Node* curr = NULL;
int n;
printf("Enter elements of the set in ascending order (-1 to stop): ");
scanf("%d", &n);
while (n != -1) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = n;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
curr = newNode;
}
else {
curr->next = newNode;
curr = newNode;
}
scanf("%d", &n);
}
return head;
}
void printSet(Node* head) {
Node* curr = head;
if (curr == NULL) {
printf("{}\n");
return;
}
printf("{");
while (curr->next != NULL) {
printf("%d, ", curr->data);
curr = curr->next;
}
printf("%d}\n", curr->data);
}
void intersect(Node* A, Node* B) {
Node* currA = A;
Node* currB = B;
while (currA != NULL && currB != NULL) {
if (currA->data == currB->data) {
currA = currA->next;
currB = currB->next;
}
else if (currA->data < currB->data) {
Node* temp = currA->next;
free(currA);
currA = temp;
}
else {
currB = currB->next;
}
}
if (currA == NULL)
A = NULL;
else
currA->next = NULL;
}
```
阅读全文