-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHash.cs
102 lines (83 loc) · 1.98 KB
/
Hash.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class HashEntry
{
public int key
{
get; set;
}
public HashEntry(int k, int v)
{
key = k;
val = v;
}
public int val
{
get;
private set;
}
}
public class HashMap
{
private static int TABLE_SIZE = 100;
private static int EntryDeleted = -1;
private static int NoKeyFound = -2;
HashEntry[] table;
public HashMap()
{
table = new HashEntry[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = null;
}
public int get(int key)
{
int hash = (key % TABLE_SIZE);
while (table[hash] != null && table[hash].key != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] == null)
return NoKeyFound;
else
return table[hash].val;
}
public void put(int key, int value)
{
int hash = (key % TABLE_SIZE);
while (table[hash] != null && table[hash].key != EntryDeleted && table[hash].key != key)
hash = (hash + 1) % TABLE_SIZE;
table[hash] = new HashEntry(key, value);
}
public void delete(int key)
{
int hash = (key % TABLE_SIZE);
while (table[hash] != null && table[hash].key != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] != null)
{
table[hash].key = EntryDeleted;
return;
}
}
}
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
HashMap hm = new HashMap();
hm.put(3, 3);
hm.put(103, 4);
hm.put(203, 5);
hm.put(4, 44);
int k = hm.get(4);
int k1 = hm.get(203);
hm.delete(203);
int k2 = hm.get(203);
int k3 = hm.get(4);
int k4 = 10;
}
}
}