-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseperate_chaining.js
More file actions
99 lines (83 loc) · 2.02 KB
/
seperate_chaining.js
File metadata and controls
99 lines (83 loc) · 2.02 KB
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
// SEPERATE CHAINING
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
class HashTable {
constructor(size = 100) {
this.table = new Array(size);
this.length = 0;
}
// hash table index degeri bulma
hash(key){
return key.toString().length % this.size.length;
}
add(item){
// yeni index degeri verir
let index = this.hash(item);
// node degeri olusturmak
let node = new Node(item);
// eger deger varsa node ile bir sonraki (next) degerine deger atiyoruz
if(this.table[index])
node.next = this.table[index]
//eger deger yoksa n
this.table[index] = node;
}
search(item){
for (let i = 0; i < this.table.length; i++) {
if(this.table[i]){
let current = this.table[i];
while(current){
if(current.data === item)
return true;
}
current = current.next;
}
}
return false;
}
remove(item) {
let index = this.hash(item);
if(this.table[index]){
if(this.table[index].data === item){
this.table[key] = this.table[key].next;
}
else{
let current = this.table[key].next;
let prev = this.table[key];
while(current){
if(current.data === item)
prev.next = current.next;
prev = current;
current = current.next;
}
}
}
return false;
}
size(){
let counter = 0;
for(let i = 0; i < this.table.length; i++){
if(this.table[i]){
let current = this.table[i];
while(current){
counter++;
current = current.next;
}
}
}
return counter;
}
isEmpty() {
return this.size() < 1 ? true : false;
}
}
const ht = new HashTable();
ht.add("Canada");
ht.add("Germany");
ht.add("Italy");
ht.add("Ahmoo");
console.log(ht.search("Canada"));
console.log(ht);