gpt4 book ai didi

c - 链接列表和结构

转载 作者:太空宇宙 更新时间:2023-11-04 08:56:43 25 4
gpt4 key购买 nike

我正在做一个学校项目,我想更好地理解双向链表和结构。目前,我正在尝试实现一个函数,一个创建新链表的函数。因为我认为我可以在那里工作。

typedef struct ListItem {
struct ListItem *previousItem; //pointer to previous item, NULL if first list item
struct ListItem *nextItem; //pointer to next item, NULL if first list item
void *data; //pointer to data

这是我要创建的双向链表的结构。我知道“void *”可以包含指向任何内容的指针,而且我必须分配存储在列表项中的任何数据。

/**
* This function starts a new linked list. Given an allocated pointer to data it will return a
* pointer for a malloc()ed ListItem struct. If malloc() fails for any reason, then this function
* returns NULL otherwise it should return a pointer to this new list item. data can be NULL.
*
* @param data The data to be stored in the first ListItem in this new list. Can be any valid
* pointer value.
* @return A pointer to the malloc()'d ListItem. May be NULL if an error occured.
*/

ListItem *NewList(void *data);

我知道 malloc() 在堆栈上分配了足够的内存供使用,所以我认为在我的函数中我必须 malloc() *previousItem、*nextItem 和 *data(这将是 6 个字节?)除了那,要实现该功能,我要做的就是复制 ListItem 结构?上一个和下一个项目将是 NULL 指针,因为它是列表中的唯一项目,*data 将是我认为的输入。谁能告诉我我的代码是什么样子的?

最佳答案

您走在正确的轨道上。您可以使用 sizeof 来获取需要分配的内存量,而不是使用 6 作为 malloc 的参数 - 例如:

ListItem *node = malloc(sizeof(ListItem));

之后的实现就相当简单了:

/* Make sure that allocation succeeded */
...
/* Assign the right values to previousItem and nextItem */
...
/* Assign the right value to data */
...
/* Return the pointer to the new list */
...

其他人可能会提交完整的功能,但您对需要发生的事情的英语描述是正确的(除了整个堆与堆栈的事情)。

关于c - 链接列表和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16574805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com