Remove Duplicates From an Unsorted Linked List

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <cstring>
using namespace std;

typedef struct node{
    int data;
    node *next;
}node;
bool myhash[100];

node* init(int a[], int n){
    node *head, *p;
    for(int i=0; i<n; ++i){
        node *nd = new node();
        nd->data = a[i];
        if(i==0){
            head = p = nd;
            continue;
        }
        p->next = nd;
        p = nd;
    }
    return head;
}
void removedulicate(node *head){
    if(head==NULL) return;
    node *p=head, *q=head->next;
    myhash[head->data] = true;
    while(q){
        if(myhash[q->data]){
            node *t = q;
            p->next = q->next;
            q = p->next;
            delete t;
        }
        else{
            myhash[q->data] = true;
            p = q; q = q->next;
        }
    }
}
void removedulicate1(node *head){
    if(head==NULL) return;
    node *p, *q, *c=head;
    while(c){
        p=c; q=c->next;
        int d = c->data;
        while(q){
            if(q->data==d){
                node *t = q;
                p->next = q->next;
                q = p->next;
                delete t;
            }
            else{
                p = q; q = q->next;
            }
        }
        c = c->next;
    }
}
void print(node *head){
    while(head){
        cout<<head->data<<" ";
        head = head->next;
    }
    cout<<endl;
}
int main(){
    int n = 10;
    int a[] = {
        3, 2, 1, 3, 5, 6, 2, 6, 3, 1
    };
    memset(myhash, false, sizeof(myhash));
    node *head = init(a, n);
    removedulicate1(head);
    print(head);
    return 0;
}