c++ - 使用散列从链表中删除重复项

标签 c++ linked-list

我尝试使用散列从链接列表中删除重复项。不是使用unordered_map,而是使用 vector 来跟踪出现的情况。我运行了一个简单的测试用例,但得到了我不明白的结果。 我的代码是:

class Solution {
   public:
         Node* removeDuplicates(Node *head) {
             vector<int> vec{10000 , 0};
             auto tmp = head;
             auto tmp2 = tmp;
             while (tmp) {
                 vec[tmp->data]++;
                 cout << "Data : " << tmp->data << " counter " << vec[tmp->data] << "\n";
                 if (vec[tmp->data] > 1) {                     
                     tmp2->next = tmp2->next->next;
                 }
                 tmp2 = tmp;
                 tmp = tmp->next;
             }
             return head;
         }

我尝试了以下测试用例 2 3 3 4 6. 这是链表中节点的数据。

我得到的结果是这样的。

Data : 2 counter 1
Data : 3 counter 1
Data : 3 counter 2
Data : 4 counter 1
Data : 6 counter 4114

2 3 4 

实际结果应该是

Data : 2 counter 1
Data : 3 counter 1
Data : 3 counter 2
Data : 4 counter 1
Data : 6 counter 1

2 3 4 6

最佳答案

vector<int> vec{10000, 0};创建一个包含两个元素的 vector 100000 ,使用采用 std::initializer_list 的构造函数:

vector(std::initializer_list<T> init, const Allocator& alloc = Allocator());

您很可能需要vector<int> vec(10000, 0); 。这将创建一个包含 10000 个元素的 vector ,初始化为 0 ,使用

vector(size_type count, const T& value, const Allocator& alloc = Allocator());

标准reads [over.match.list] :

When objects of non-aggregate class type T are list-initialized such that [dcl.init.list] specifies that overload resolution is performed according to the rules in this subclause, overload resolution selects the constructor in two phases:

  • Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T and the argument list consists of the initializer list as a single argument.
  • If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

关于c++ - 使用散列从链表中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56769150/

相关文章:

c - 使用 valgrind 时大小为 1 的读取无效

java - 您如何测试 Iterator/ListIterator 是否有效?

c++ - 带节点删除函数的链表问题

c++ - 将外部变量传递给类 C++

Thrift 生成结构的 C++ 大括号初始化

c++ - 是否可以使函数模板从函数引用中获取 `decltype`?

C# 使用 base 中的链表数据结构

c++ - OpenCV:如何使用 Haar Classifier Cascade 提高眼睛检测的准确性?

c++ - 在 STL 中使用 void* 作为固定宽度的记录

java - List、ArrayList 和 LinkedList 有问题吗?