对单链表A、B,编写算法求A=A∩B,A=A∪B的完整代码
时间: 2023-06-17 16:05:40 浏览: 44
以下是求A=A∩B,A=A∪B的完整代码(C++实现):
```cpp
#include <iostream>
#include <unordered_set>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
unordered_set<ListNode*> set;
ListNode* cur = headA;
while (cur != NULL) {
set.insert(cur);
cur = cur->next;
}
cur = headB;
while (cur != NULL) {
if (set.count(cur) > 0) {
return cur;
}
cur = cur->next;
}
return NULL;
}
void mergeList(ListNode* headA, ListNode* headB) {
ListNode* curA = headA, * curB = headB;
while (curA != NULL && curB != NULL) {
if (curA->val < curB->val) {
curA = curA->next;
}
else if (curA->val > curB->val) {
ListNode* tmp = curB->next;
curB->next = curA;
headA = curB;
curB = tmp;
}
else {
curA = curA->next;
curB = curB->next;
}
}
if (curB != NULL) {
ListNode* tailA = headA;
while (tailA->next != NULL) {
tailA = tailA->next;
}
tailA->next = curB;
}
}
int main() {
// 构造链表 A
ListNode* headA = new ListNode(1);
headA->next = new ListNode(2);
headA->next->next = new ListNode(3);
headA->next->next->next = new ListNode(4);
// 构造链表 B
ListNode* headB = new ListNode(2);
headB->next = new ListNode(4);
headB->next->next = new ListNode(6);
// 求 A=A∩B
ListNode* intersection = getIntersectionNode(headA, headB);
if (intersection != NULL) {
ListNode* cur = headA;
while (cur != intersection) {
cur = cur->next;
headA = headA->next;
}
while (cur != NULL) {
cur = cur->next;
headA = headA->next;
}
headA = NULL;
}
// 求 A=A∪B
mergeList(headA, headB);
// 输出链表 A
ListNode* cur = headA;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
return 0;
}
```
其中,`getIntersectionNode`函数用于求A=A∩B,`mergeList`函数用于求A=A∪B。在主函数中,我们构造了链表A和链表B,并分别调用了这两个函数来求解两个问题。最后输出链表A的所有节点值。