C++删除单链表中值重复的结点

来源:互联网 发布:json 汉字 编辑:程序博客网 时间:2024/06/16 07:31
#include <iostream>
#include <set>


struct Node {
int value;
Node *next;
Node(int data) : value(data), next(nullptr) {};
};


void delRepeatNode(Node * head);
void print(Node *head);
bool find(const std::set<int> &set, int value);


int main()
{
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(1);
Node n5(5);
Node n6(1);
Node n7(7);
Node n8(1);


n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
n6.next = &n7;
n7.next = &n8;


std::set<int> set;
set.insert(15);
set.insert(5);


delRepeatNode(&n1);
print(&n1);


system("pause");
return 0;
}


void delRepeatNode(Node * head) //删除重复结点函数
{
if (head == nullptr)
{
return;
}
std::set<int> hash;
Node *pre = head;
Node *cur = head->next;


hash.insert(head->value);//构造hash表,并且检查当前结点是否在hash表中存在
while (cur != nullptr)
{
if (find(hash, cur->value))
{
pre->next = cur->next;
}
else
{
hash.insert(cur->value);
pre = cur;
}
cur = cur->next;
}
}


void print(Node *head) //打印函数
{
while (head != nullptr)
{
std::cout << head->value << std::endl;
head = head->next;
}
}


bool find(const std::set<int> &set, int value) //在hash表中查看是否value的值已经存在
{
std::set<int>::iterator it = set.begin();//通过迭代器遍历set
for (; it != set.end(); ++it)
{
if (*it == value)
{
return true;
}
}
return false;
}
原创粉丝点击