c++删除单链表指定值结点

#include 
#include 

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 &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 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 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 &set, int value) //在hash表中查看是否value的值已经存在
{
    std::set::iterator it = set.begin(); //通过迭代器遍历set
    for (; it != set.end(); ++it)
    {
        if (*it == value)
        {
            return true;
        }
    }
    return false;
}

你可能感兴趣的:(算法及数据结构)