-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path705.cpp
113 lines (106 loc) · 2.5 KB
/
705.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
struct node
{
int key;
struct node *next;
node(int k) : key(k) { next = NULL; }
};
class MyHashSet
{
private:
vector<node *> buckets;
int hash(int key)
{
int m = buckets.size();
return key % m;
}
public:
/** Initialize your data structure here. */
MyHashSet()
{
for (int i = 0; i < 13000; i++)
{
buckets.push_back(NULL);
}
}
~MyHashSet()
{
node *curr;
node *temp;
for (int i = 0; i < 13000; i++)
{
curr = buckets[i];
while (curr != NULL)
{
temp = curr->next;
delete curr;
curr = temp;
}
}
temp = NULL;
curr = NULL;
}
void add(int key)
{
int index = hash(key);
if(buckets[index] == NULL)
buckets[index] = new node(key);
else{
node* curr = buckets[index];
node* prev;
while(curr != NULL){
if(key == curr->key){
return;
}
else{
prev = curr;
curr = curr->next;
}
}
curr = new node(key);
prev->next = curr;
}
}
void remove(int key)
{
int index = hash(key);
node* curr = buckets[index];
node* prev = NULL;
while(curr != NULL){
if(curr->key == key){
if(prev != NULL) // deleting middle node
prev->next = curr->next;
else //if deleting head with other linked nodes or solo head node
buckets[index] = curr->next;
delete curr;
curr = NULL;
}
else{
prev = curr;
curr= curr->next;
}
}
}
/** Returns true if this set contains the specified element */
bool contains(int key)
{
int index = hash(key);
if(buckets[index] == NULL)
return false;
else{
node* curr = buckets[index];
while(curr != NULL){
if(curr->key == key)
return true;
curr= curr->next;
}
}
return false;
}
};
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet obj = new MyHashSet();
* obj.add(key);
* obj.remove(key);
* bool param_3 = obj.contains(key);
*/