使用map做数组与链表去重

#include<iostream>
#include<map>
using namespace std;

class node{
public:
    node():value(0),next(NULL){}
    ~node(){}
    int value;
    node* next;
};///be careful this ;


node* createlist(int a[],int n)
{
 node* startnode = new node[n];
 node* ret = startnode;
 for(int i = 0;i<n;i++)
 {
     startnode[i].value = a[i];
     if(i<n-1) 
         startnode[i].next = startnode + i + 1;
 }
 cout<<endl;
 return ret;
}

void arraydeletedoublebymap()
{
    int a[] = {1,5,7,8,9,9,8,7,5,4,2,4,2,3,4};
   // node * t = createlist(a,sizeof(a)/sizeof(a[0]));
    map<int,int> m;
    for(int i = 0;i<sizeof(a)/sizeof(a[0]);i++)
    {
        m.insert(pair<int,int>(a[i],1));
    }
    
    for(map<int,int>::iterator it = m.begin();it != m.end();it++)
    {cout<<it->first;} ///其实输出的结果也是排序过的
}

node* deletenode(node * t)
{
    node* ret = t->next;
    //delete t;
    return ret;
}

void helper(node * head)
{
    map<int,int> m;
    node* ret = head;
    m.insert(pair<int,int>(head->value,1));
    node* pre = head;
    head = head->next;
    while(head)
    {
        cout<<head->value<<endl;
        pair<map<int,int>::iterator,bool> ret = m.insert(pair<int,int>(head->value,1));
        if(ret.second == false) 
        {
            pre->next = deletenode(head);
            head = pre->next;
        }else{
            pre = head;
            head = head->next;
        }
    }
    
    while(ret)
    {
        cout<<ret->value<<" ";
        ret = ret->next;
    }
}

int main()
{
    int a[] = {1,5,7,8,9,9,8,7,5,4,2,4,2,3,4};
    node * t = createlist(a,sizeof(a)/sizeof(a[0]));
    helper(t);
}
berkeleysong
原文地址:https://www.cnblogs.com/berkeleysong/p/3740795.html