2014-05-17 27 views
0

所以我的数据结构应该是一个哈希表,一个链表的数组。在每个链表中都有一个链表。在这些链接列表里面有一本书。一本书包含一本书名,以及一本藏书的链接列表库ID。在另一个结构中访问struct字段

我在链接列表中查找是否存在book->名称时遇到问题。 我知道如何访问所谓的“架子”,它是由:

int index = hashFunction(char* nameOfBook) % this->size; 

,然后哈希阵列内搜索找到这样的:

this->chain[index] 

但我怎么能访问Book结构一旦我在链接列表中?

在list.h

typedef struct NodeStruct { 
    void *data; 
    struct NodeStruct* next; 
    struct NodeStruct* prev; 
} NodeStruct; 

typedef struct ListStruct { 
    NodeStruct* first; 
    NodeStruct* last; 
    int elementType; 
} ListStruct; 

在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; 

下面是构造函数:

// 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; 
} 

编辑:我觉得它得工作。还没有测试过。

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; 
} 

对不起,如果这是非常混乱。顺便说一句,链表的'数据'是通用的。 谢谢!

+0

'for(int i = 0; i chain [i] = newList(sizeof(Book *));}'没有意义。也许:'for(int i = 0; i chain [i] = NULL;}'? – wildplasser

+0

嗨,为什么不初始化所有的链表?分别初始化每一个更好吗? – Mickey

回答

1

因为cur->data是指向void的指针,所以您需要将它分配给类型为Book(或将其强制转换为该类型)的指针。否则,您将无法使用->获得成员,因为void不是结构体。

您在编辑中修复的内容应该可以正常工作。

+0

感谢您的编辑,我没有校对过。 – McLovin

+0

这给我段错误:( – Mickey

相关问题