-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash.h
93 lines (72 loc) · 1.78 KB
/
hash.h
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
#include <iostream>
#include <cstdlib>
#include <vector>
#include "song.h"
using namespace std;
class Hash {
private:
struct songStruct {
Song song;
songStruct* next;
songStruct* prev;
};
static const int tableSize = 100;
songStruct* hashMap[tableSize];
public:
Hash();
int hash(string key);
void AddSong(Song newSong);
int NumberOfItemsInIndex(int index);
void PrintTable();
void PrintItemsInIndex(int index);
Song* FindSong(string name, string artist);
void RemoveItem(string title);
int count = 0;
};
Hash::Hash(){
for (int i = 0; i < tableSize; ++i) {
hashMap[i] = new songStruct;
hashMap[i]->next = nullptr;
hashMap[i]->prev = nullptr;
}
}
void Hash::AddSong(Song newSong) {
int index = hash(newSong.name);
if (hashMap[index]->song.name.empty())
{
hashMap[index]->song = newSong;
}
else
{
songStruct* Ptr = hashMap[index];
songStruct* n = new songStruct;
n->song = newSong;
n->next = nullptr;
while(Ptr->next != nullptr)
{
Ptr = Ptr->next;
}
Ptr->next = n;
}
}
int Hash::hash(string key) {
int hash = 0;
int index;
for (int i = 0; i < key.length(); i++) {
hash = hash + (int) key[i];
}
index = hash % tableSize;
if (index < 0) { index*=-1;}
return index;
}
Song* Hash::FindSong(string name, string artist) {
int index = hash(name);
songStruct* Ptr = hashMap[index];
while (Ptr != nullptr) {
if (Ptr->song.name == name && Ptr->song.artists == artist) {
return &(Ptr->song); // Return the address of the found song
}
Ptr = Ptr->next;
}
return nullptr; // Return nullptr if not found
}