简体   繁体   English

从双向链表中删除重复项

[英]Delete duplicates from Doubly linked list

Hello I stumbled following question You given unsorted doubly linked list.You should find and delete duplicates from Doubly linked list.您好,我偶然发现了以下问题,您给出了未排序的双向链表。您应该从双向链表中查找并删除重复项。

What is the best way to do it with minimum algorithmic complexity?以最小的算法复杂度做到这一点的最佳方法是什么?

Thank you.谢谢你。

If the space is abundance and you have to really optimize this with time, perhaps you can use a Hashset (or equivalent in C++).如果空间充足并且您必须随着时间的推移真正优化它,也许您可以使用Hashset (或 C++ 中的等价物)。 You read each element and push it to the hashset.您读取每个元素并将其推送到哈希集。 If the hashset reports a duplicate, it means that there is a duplicate.如果哈希集报告重复,则表示存在重复。 You simply would delete that node.您只需删除该节点。

The complexity is O(n)复杂度为O(n)

Think of it as two singly linked lists instead of one doubly linked list, with one set of links going first to last and another set going last to first.把它想象成两个单链表而不是一个双链表,一组链接从头到尾,另一组从尾到头。 You can sort the second list with a merge sort, which will be O(n log n).您可以使用合并排序对第二个列表进行排序,即 O(n log n)。 Now traverse the list using the first link.现在使用第一个链接遍历列表。 For each node, check if (node.back)->key==node.key and if so remove it from the list.对于每个节点,检查是否(node.back)->key==node.key ,如果是,则将其从列表中删除。 Restore the back pointer during this traversal so that the list is properly doubly linked again.在此遍历期间恢复反向指针,以便列表再次正确地进行双重链接。

This isn't necessarily the fastest method, but it doesn't use any extra space.这不一定是最快的方法,但它不使用任何额外的空间。

Assuming that the potential employer believes in the C++ library:假设潜在雇主相信 C++ 库:

// untested O(n*log(n))
temlate <class T>
void DeDup(std::list<T>& l) {
    std::set<T> s(l.begin(), l.end());
    std::list<T>(s.begin(), s.end()).swap(l);
}

With minimum complexity?以最小的复杂性? Simply traverse the list up to X times (where X is the number of items), starting at the head and then delete (and reassign pointers) down the list.只需遍历列表 X 次(其中 X 是项目数),从头部开始,然后在列表中删除(并重新分配指针)。 O(n log n) (I believe) time at worse case, and really easy to code. O(n log n) (我相信)时间在最坏的情况下,而且真的很容易编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM