-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashTable.h
More file actions
109 lines (98 loc) · 1.99 KB
/
hashTable.h
File metadata and controls
109 lines (98 loc) · 1.99 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
// Iris Favorial, Yeseul An - Assignment 4 Implementation - CSS343
// purpose:
// The hashtable class which is to hash using the customers unique ID
// Assumes that the customer has unique ID and they are properly formatted
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include "customer.h"
using namespace std;
template <class Type>
class HashTable
{
static const int SIZE = 53; // prime number, more than twice larger than customer size
public:
HashTable() // constructor
{
for(int i = 0; i < SIZE; i++)
{
table[i] = NULL;
}
}
~HashTable() // destructor
{
for (int i = 0; i < SIZE; i++)
{
if (table[i] != NULL)
{
ItemList *del = table[i];
while (table[i] != NULL)
{
table[i] = table[i]->next;
delete del->data;
delete del;
del = table[i];
}
}
}
}
Type *retrieve(int key) const // retrieve value in the table
{
int hashKey = key % SIZE;
if (table[hashKey] == NULL)
{
return NULL;
}
else
{
ItemList *cur = table[hashKey];
while (cur != NULL)
{
if (key == cur->key)
{
return cur->data;
}
else
{
cur = cur->next;
}
}
}
return NULL;
}
void insert(int key, Type *item) // inserts an item to the hashtable
{
int hashKey = key % SIZE;
ItemList *newItem = new ItemList;
newItem->data = item;
newItem->key = key;
newItem->next = NULL;
if (table[hashKey] == NULL)
{
table[hashKey] = newItem;
}
else
{
ItemList *cur = table[hashKey];
while (cur->next != NULL)
{
if (key == cur->key)
{
delete newItem->data;
delete newItem;
}
cur = cur->next;
}
cur->next = newItem;
}
}
private:
struct ItemList // the struct in the hashtable
{
Type *data;
int key;
ItemList *next;
};
ItemList *table[SIZE]; // hashtable
};