2.1-链表去重

来源:互联网 发布:带着淘宝混异世文汇吧 编辑:程序博客网 时间:2024/06/03 19:43

Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?

链表去重

1.用hash来检测重复,O(n)

2.遍历链表的同时,每次检索之前的所有元素是否有重复,有的话就删除当前节点, O(n^2)

#include <iostream>#include <hash_map.h>using namespace std;struct ListNode{    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};void show(ListNode *head){    while(head)    {        cout<<head->val;        head = head->next;    }    cout<<endl;}ListNode *createLinkedlist(int array[], int len){    ListNode *cur = new ListNode(0);    ListNode *head=cur;    for(int i=0; i<len; i++)    {        ListNode *p = new ListNode(array[i]);        cur->next=p;        cur=cur->next;    }    cur->next=NULL;    return head->next;}void removeDuplicates_Hash(ListNode *head){    if(head==NULL || head->next==NULL)        return;    ListNode *cur=head,*pre=head;    hash_map<int, int> hashmap;    while(cur)    {        if(hashmap.find(cur->val) != hashmap.end())//exist        {            pre->next=cur->next;        }        else        {            hashmap[cur->val]=1;            pre=cur;        }        cur = cur->next;    }}void removeDuplicates_O2(ListNode *head){    if(head==NULL || head->next==NULL)        return;    ListNode *cur=head->next,*pre=head;    ListNode *pre_itor=head;    while(cur)    {        while(pre_itor!=cur)        {            if(pre_itor->val==cur->val)            {                pre->next=cur->next;                break;            }            pre_itor = pre_itor->next;        }        if(pre_itor==cur)            pre=cur;        cur = cur->next;        pre_itor=head;    }}int main(){    int a[] = {1,2,3,4,5,2,3,2,1,1,1,1};    ListNode *head = createLinkedlist(a,12);    show(head);    removeDuplicates_Hash(head);    show(head);    ListNode *head2 = createLinkedlist(a,12);    removeDuplicates_O2(head2);    show(head2);    return 0;}



0 0