2.1-链表去重

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值