-
-
Notifications
You must be signed in to change notification settings - Fork 486
Expand file tree
/
Copy pathHashing.dart
More file actions
130 lines (106 loc) · 2.04 KB
/
Hashing.dart
File metadata and controls
130 lines (106 loc) · 2.04 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//Author:Shawn
//Email:stepfencurryxiao@gmail.com
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
int size;
LinkedList() {
head = null;
size = 0;
}
void insert(int data) {
Node newnode = new Node(data);
size++;
if (head == null) {
head = newnode;
} else {
newnode.next = head;
head = newnode;
}
}
void delete(int data) {
if (size == 0) {
print("underFlow!");
return;
} else {
Node curr = head;
if (curr.data == data) {
head = curr.next;
size--;
return;
} else {
while (curr.next.next != null) {
if (curr.next.data == data) {
curr.next = curr.next.next;
return;
}
}
print("Key not found");
}
}
}
void display() {
Node temp = head;
while (temp != null) {
print(temp.data.toString());
temp = temp.next;
}
print("\n");
}
}
class HashMap {
int hsize;
List<LinkedList> buckets;
HashMap(int hsize) {
buckets = []..length = hsize;
for (int i = 0; i < hsize; i++) {
buckets[i] = new LinkedList();
}
this.hsize = hsize;
}
int hashing(int key) {
int hash = key % hsize;
if (hash < 0) {
hash += hsize;
}
return hash;
}
void insertHash(int key) {
int hash = hashing(key);
buckets[hash].insert(key);
}
void deleteHash(int key) {
int hash = hashing(key);
buckets[hash].delete(key);
}
void displayHashtable() {
for (int i = 0; i < hsize; i++) {
print("Bucket $i:");
buckets[i].display();
}
}
}
void main() {
HashMap h = new HashMap(7);
print("Add key 5");
h.insertHash(5);
print("Add key 28");
h.insertHash(28);
print("Add key 1");
h.insertHash(1);
print("Delete Key 28");
h.deleteHash(28);
print("Print Table:\n");
h.displayHashtable();
print("Delete Key 1");
h.deleteHash(1);
print("Print Table:\n");
h.displayHashtable();
}