删除无序单链表中值重复出现的节点

#include "List.h"
#include <map>
using namespace std;

//时间复杂度O(N), 空间复杂度O(N)
//使用一个额外的空间保存数据,也可以用一个bool型的数组,保存所有可能的int值
//这样可以达到O(1)的空间复杂度,但是这个O(1)特别大
void removerep1(Node* head)
{
    if(head == nullptr)
        return;
    map<int, Node*> nMap;

    Node* pre = head;
    Node* cur = head->next;
    nMap[pre->value] = pre;
    while(cur)
    {
        if(nMap.find(cur->value) != nMap.end())
            pre->next = cur->next;
        else
        {
            nMap[cur->value] = cur;
            pre = cur;
        }
        cur = cur->next;
    }
}
//时间复杂度N^2,空间复杂度1
void removerep2(Node* head)
{
    Node* cur = head;
    Node* pre = nullptr;
    Node* next = nullptr;

    while(cur)
    {
        pre = cur;
        next = cur->next;
        while(next)
        {
            if(next->value == cur->value)
                pre->next = next->next;
            else
                pre = next;
            next = next->next;
        }
        cur = cur->next;
    }
}

int main()
{
    Node* pNode0 = new Node(0);
    Node* pNode1 = new Node(1, pNode0);
    Node* pNode2 = new Node(2, pNode1);
    Node* pNode3 = new Node(2, pNode2);
    Node* pNode4 = new Node(1, pNode3);
    Node* pNode5 = new Node(0, pNode4);

    removerep2(pNode5);
    Print(pNode5);
}



猜你喜欢

转载自blog.csdn.net/wzc2608/article/details/80682540