简体   繁体   English

C中的链表

[英]Linkedlist in C

I am trying to create a linkedlist in C with pointers to structs at the moment. 我正在尝试用C指针创建指向结构的链表。 I am having some issues with my logic. 我的逻辑有些问题。 So I was wondering, when removing the head of the list, would I return the removed item, OR, would I return the new head of the list. 所以我想知道,当删除列表的开头时,我是否返回已删除的项目,或者是否返回列表的新开头。 Also if I would return the new head, how would I free the memory? 另外,如果我要退回新的磁头,该如何释放内存? (This part is for an assignment) According to the assignment information, we are not supposed to free the removed item in the function. (此部分用于分配)根据分配信息,我们不应该释放函数中已删除的项目。 So yea, my question is, where would I free the memory? 是的,我的问题是,我应该在哪里释放内存? Here is that snippet of code. 这是那段代码。 My code here just returns the new head, or returns NULL if the list is empty. 我的代码只是返回新的头,如果列表为空,则返回NULL。

MusicRec * removeFromFront(MusicRec * theList)
{
    if(theList == NULL)
    {
        return NULL;
    } 
    return theList->next;
}

Simple. 简单。 Every allocation function has a companion deallocation function, and sometimes a whole suite of additional utility functions. 每个分配功能都有一个伴随的解除分配功能,有时还有一整套附加的实用程序功能。 Look in the docs for your allocator. 在文档中查找您的分配器。

Deallocate just before you return. 返回之前就取消分配。 That might mean you need a temporary copy. 这可能意味着您需要一个临时副本。

BTW: You are returning the proper value... 顺便说一句:您正在返回正确的值...

MusicRec *removeFromFront(MusicRec  **theListref)
{
    if(*theListref == NULL)
        return NULL;    // shouldn't there be an underflow error?
    Musicref *oldhead = *theListref;
    *theListref = *theListref->next;
    return oldhead;
}

I'm returning the pointer to old head. 我将指针返回到旧头。 This can be freed in the calling function. 可以在调用函数中将其释放。 The parameter is a reference to the current head pointer. 该参数是对当前头指针的引用

EDIT If I have to stick to your interface, your code is perfectly all right & I'll clean up memory in the calling function: 编辑如果我必须坚持使用您的界面,那么您的代码就可以了,我将清理调用函数中的内存:

theListCopy = theList;
theList = removeFromFront(theList);
//free the ListCopy here

The function should save a pointer to the node being removed (the current head node), reset the head of the list to the next node (ie the current 2nd node) and then return the saved pointer to the removed node. 该函数应保存指向要删除的节点(当前头节点)的指针,将列表的开头重置为下一个节点(即当前的第二个节点),然后将保存的指针返回到已删除的节点。

The user using your linked list api may have some complex structure being used as the node and in that case it is best left up to the caller to handle the memory cleanup of the data. 使用您的链接列表api的用户可能具有一些复杂的结构用作节点,在这种情况下,最好由调用方来处理数据的内存清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM