入参为两个单链表,带空头节点。单个链表中的元素都没有重复,但两个链表的元素存在重复元素。请合并两个链表,并移除其中的重复元素。例如: 链表1:1->2->3->4->5->^ 链表2:2->4->1->8->6->^ 结果:1->2->3->4->5->8->6->^
时间: 2024-10-25 14:09:21 浏览: 30
要合并并去除重复元素的链表,你可以采用哈希集合(如 C++ 中的 unordered_set)来帮助跟踪已经遇到过的元素。以下是 C++ 的解决方案:
```cpp
#include <unordered_set>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* mergeAndRemoveDuplicates(ListNode* head1, ListNode* head2) {
unordered_set<int> seenValues;
ListNode* dummy = new ListNode(0); // 新的头节点
ListNode* tail = dummy; // 尾节点指向dummy
while (head1 != nullptr || head2 != nullptr) {
if (head1 == nullptr) {
tail->next = head2;
head2 = head2->next;
} else if (head2 == nullptr) {
tail->next = head1;
head1 = head1->next;
} else if (seenValues.find(head1->val) == seenValues.end()) { // 遇到未见过的值
tail->next = head1;
seenValues.insert(head1->val);
head1 = head1->next;
} else { // 遇到重复值,跳过
head2 = head2->next;
}
tail = tail->next;
}
return dummy->next; // 返回新的头节点
}
int main() {
ListNode* list1 = new ListNode{1, new ListNode{2, new ListNode{3, new ListNode{4, new ListNode{5}}}}};
ListNode* list2 = new ListNode{2, new ListNode{4, new ListNode{1, new ListNode{8, new ListNode{6}}}}};
ListNode* mergedList = mergeAndRemoveDuplicates(list1, list2);
// 打印合并后的链表
while (mergedList != nullptr) {
cout << mergedList->val << " ";
mergedList = mergedList->next;
}
return 0;
}
```
这个函数会创建一个新链表,其中包含从头1开始到头2结束,且没有重复值的元素。
阅读全文
相关推荐

















