Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)
Paste
Pasted as C++ by dsf ( 16 years ago )
#include <iostream>
#include <cstring>
#include <stdlib.h>
const unsigned short TABLE_SIZE = 10;
using namespace std;
typedef string t_key; // 10 char + \0
typedef struct {
int id;
} t_record;
struct t_cell {
t_record record;
t_key key;
struct t_cell * next;
};
t_cell * hashtable[TABLE_SIZE];
int myhash(t_key);
bool add_record(t_key, t_record record);
bool edit_record(t_key, t_record record);
bool delete_record(t_key);
bool get_record(t_key key, t_record * record);
void assert_key(t_key key);
int main(int argc, char** argv) {
for(int i = 0; i < TABLE_SIZE; i++) {
hashtable[i] = NULL;
}
string k1("test");
string k2("im");
string k3("love");
string k4("okou");
string k5("beaucouptroplong");
t_record r1;
r1.id = 3;
t_record r2;
r2.id = 5;
t_record r3;
r3.id = 9;
t_record r4;
r4.id = 7;
add_record(k1, r1);
add_record(k2, r2);
add_record(k3, r3);
t_record lire;
if(get_record(k1, &lire;)) {
cout << "find : " << lire.id << endl;
}
else {
cout << "not find" << endl;
}
if(get_record(k2, &lire;)) {
cout << "find : " << lire.id << endl;
}
else {
cout << "not find" << endl;
}
if(get_record(k3, &lire;)) {
cout << "find : " << lire.id << endl;
}
else {
cout << "not find" << endl;
}
if(get_record(k4, &lire;)) {
cout << "find : " << lire.id << endl;
}
else {
cout << "not find" << endl;
}
add_record(k5, r2);
return 0;
}
int myhash(t_key key) {
assert_key(key);
return key.size();
}
bool add_record(t_key key, t_record record) {
assert_key(key);
int hash = myhash(key);
t_cell * current = hashtable[hash];
bool ret = true;
t_cell * cellule = new t_cell;
cellule->record = record;
cellule->next = NULL;
cellule->key = key;
if(hashtable[hash]==NULL) {
hashtable[hash] = cellule;
}
else {
bool sortir = false;
while(!sortir) {
if(current->key==key) {
ret = false;
sortir = true;
}
else if(current->next==NULL) {
sortir = true;
}
else {
current = current->next;
}
}
if(ret) {
current->next = cellule;
}
}
return ret;
}
bool edit_record(t_key key, t_record record) {
assert_key(key);
}
bool delete_record(t_key key) {
assert_key(key);
}
bool get_record(t_key key, t_record * record) {
assert_key(key);
int hash = myhash(key);
t_cell * current = hashtable[hash];
bool isFind = false;
while(!isFind && current!=NULL) {
if(current->key==key) {
isFind = true;
record->id = (current->record).id;
}
else {
current = current->next;
}
}
return isFind;
}
void assert_key(t_key key) {
if(key.size()<0 || key.size()>TABLE_SIZE) {
cout << "Le nombre de caractère de la clé doit être entre 1 et " << TABLE_SIZE << "." << endl;
exit(1);
}
}
Revise this Paste
Children: 15727