【问题标题】:A Hashset that holds a generic linked list that holds a generic linked list一个包含通用链表的 Hashset,该链表包含一个通用链表
【发布时间】:2014-07-04 09:32:28
【问题描述】:

这是我在课堂上做的作业的数据结构。我应该实现一个包含一串链表的哈希集。这些单独的链表中的每一个都包含一个 int。我的列表是通用的,如果可行的话,使用 (void* data) 像这样:

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

 //  Rename NodeStruct* as NodePtr
 typedef NodeStruct* NodePtr;

 typedef struct ListStruct {
     int elementType;
     NodePtr first;
     NodePtr last;
     NodePtr current;
 } ListStruct;

 //  ListHndl is just a ListStruct* renamed.

第一个问题:现在,我正在使用memcpy(list->data, data, list->elementType)。 我想知道..直接存储可以吗,比如list->data = data

这是我的哈希集结构:

 typedef struct HashStruct {
     int size;
     int load;
     ListHndl *chain; //An array of Linked Lists.
 } HashStruct;

typedef HashStruct* HashHandle

 HashHandle new_hashset(int size) {
     HashHandle tempHash = malloc (sizeof (HashStruct));
     assert (tempHash != NULL);
     tempHash->size = size;
     tempHash->load = 0;
     tempHash->chain = malloc (sizeof (ListHndl) * size);
     assert(tempHash->chain != NULL);
     for (int i = 0; i < size; i++) {
         tempHash->chain[i] = newList(sizeof(char*));
         tempHash->chain[i]->data = malloc(sizeof (ListHndl)); // Error here
     }
     return tempHash;
 }

这是我遇到的错误。

hash.c: In function ‘new_hashset’:
hash.c:28:27: error: dereferencing pointer to incomplete type
         tempHash->chain[i]->data = malloc(sizeof (ListHndl));
                           ^

第二个问题:我不确定我应该如何为这些链表分配内存,这可能就是我收到此错误的原因。

我是否正确地实现了这个数据结构?如果需要更多信息,请告诉我。谢谢!

【问题讨论】:

  • [风格提示] 去掉 typedefs;他们唯一的目的就是迷惑你。

标签: c generics hash linked-list void-pointers


【解决方案1】:

<i><b>First question:</b> Right now, I"m using memcpy(list-&gt;data, data, list-&gt;elementType). I was wondering.. is it okay do just store it directly, like list-&gt;data = data?</i>

这取决于“数据”指向什么。当 'data' 指向从堆分配的内存时,list-&gt;data = data 很常见,


<i><b>Second question:</b> I'm not sure how I'm supposed to be allocating memory for these linked lists, which is probably why I got this error.</i>

对于问题中列出的 typedef,您需要为以下各项分配内存:

  • 每个新节点:newNode=malloc(sizeof(NodeStruct))
  • 每个节点有效载荷:newNode-&gt;data = malloc(sizeof(int))

<i>Am I even implementing this data structure correctly?</i>

提供的代码有限,很难说。当然,有很多方法可以完成分配的任务;包括那些更容易理解的方式,以及那些专门针对性能进行调整的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2017-03-05
    • 2014-05-30
    相关资源
    最近更新 更多