So my data structure is supposed to be a hash table, an array of linked list. Inside each of those linked list holds a linked list. And inside those linked list is a Book. A book contains a book name, and a linked list of library IDs that hold that book.
I'm having trouble searching within the linked list to see if a book->name already exists. I know how to access the so called "shelf" that it's on by:
int index = hashFunction(char* nameOfBook) % this->size;
and then searching within the hash array to find it like this:
this->chain[index]
But how can I access the Book struct once I'm inside the linked list?
In list.h
typedef struct NodeStruct {
void *data;
struct NodeStruct* next;
struct NodeStruct* prev;
} NodeStruct;
typedef struct ListStruct {
NodeStruct* first;
NodeStruct* last;
int elementType;
} ListStruct;
In hash.c:
typedef struct Book {
ListStruct* libID; // Each book has its own list of library IDs
char* name; // Each book has a name.
} Book;
// A hashset contains a linked list of books.
typedef struct HashStruct {
int size;
int load;
ListStruct **chain; //An array of Linked Lists.
} HashStruct;
Here are the constructors:
// Constructor for a new book.
Book *newBook(char* name) {
Book *this = malloc (sizeof (Book));
assert(this != NULL);
this->name = name;
this->libID = malloc(sizeof (ListStruct*));
this->libID = newList(sizeof(int));
return this;
}
HashHandle new_hashset(int size) {
HashHandle tempHash = malloc (sizeof (HashStruct));
assert (tempHash != NULL);
tempHash->size = size;
tempHash->load = 0;
tempHash->chain = malloc (sizeof (ListStruct));
assert(tempHash->chain != NULL);
// Each linked list holds a linked list.
for (int i = 0; i < size; ++i) {
tempHash->chain[i] = newList(sizeof(Book));
}
return tempHash;
}
EDIT: I think I got it to work. Haven't tested yet.
bool has_hashset (HashHandle this, char *item) {
//Finds the index to look at.
int index = strhash(item) % this->size;
NodeStruct *cur = this->chain[index]->first;
while (cur != NULL) {
Book *tmp = cur->data;
if (strcmp(tmp->name, item) == 0)
return true;
cur = cur->next;
}
return false;
}
Sorry if this was very confusing. By the way, the 'data' of a linked list is generic. Thank you!
Because cur->data
is a pointer to void
, you need to assign it to a pointer of type Book
(or cast it to that type). Otherwise, you will not be able to use ->
to get a member because void
is not a struct.
What you fixed in your edit should work fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.