以下是一种 C++ 实现方案,利用有序单链表存储集合,实现交、并和差运算:
#include <iostream>
using namespace std;
struct Node {
char data;
Node *next;
};
// 两个有序链表的交集
Node* intersect(Node *first, Node *second) {
Node *head = new Node();
Node *cur = head;
while (first != nullptr && second != nullptr) {
if (first->data < second->data) {
first = first->next;
} else if (first->data > second->data) {
second = second->next;
} else {
cur->next = new Node();
cur = cur->next;
cur->data = first->data;
first = first->next;
second = second->next;
}
}
cur->next = nullptr;
return head->next;
}
// 两个有序链表的并集
Node* unionSet(Node *first, Node *second) {
Node *head = new Node();
Node *cur = head;
while (first != nullptr || second != nullptr) {
if (second == nullptr || (first != nullptr && first->data < second->data)) {
cur->next = new Node();
cur = cur->next;
cur->data = first->data;
first = first->next;
} else if (first == nullptr || second->data < first->data) {
cur->next = new Node();
cur = cur->next;
cur->data = second->data;
second = second->next;
} else {
cur->next = new Node();
cur = cur->next;
cur->data = first->data;
first = first->next;
second = second->next;
}
}
cur->next = nullptr;
return head->next;
}
// 两个有序链表的差集
Node* difference(Node *first, Node *second) {
Node *head = new Node();
Node *cur = head;
while (first != nullptr && second != nullptr) {
if (first->data < second->data) {
cur->next = new Node();
cur = cur->next;
cur->data = first->data;
first = first->next;
} else if (first->data > second->data) {
second = second->next;
} else {
first = first->next;
second = second->next;
}
}
while (first != nullptr) {
cur->next = new Node();
cur = cur->next;
cur->data = first->data;
first = first->next;
}
cur->next = nullptr;
return head->next;
}