gpt4 book ai didi

c - 在没有尾部或头的列表中插入元素

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

关于一个应该解释 malloc 工作原理的练习,我遇到了一个小问题。

对于初学者,这是我们得到的 header :

struct cell_m
{
unsigned int magicnumber ;
struct cell_m *next ;
void *userspacestart ;
void *userspacestop ;
};

typedef struct cell_m *liste_t ;

如您所见,我只有一个下一个指针,所以它是一个简单的链表。我应该编写一个函数来在 cell_mliste_t 中插入一个 cell_m

有一个条件,我们要插入的cell_m的大小必须小于我们当前所在的cell_m。这是我的这个功能的代码:

void insert(liste_t *list, liste_t cell)
{
liste_t *old_list = malloc(sizeof(liste_t*));

if (sizeof((*list)->userspacestop) - (sizeof((*list)->userspacestart))
>= (sizeof(cell->userspacestop)) - (sizeof(cell->userspacestart)))
/*insert at the begining*/
else
{
old_list = list;
(*list) = (*list)->next;
while ((*list)->next != NULL)
{
if (sizeof((*list)->userspacestop) - (sizeof((*list)->userspacestart))
>= (sizeof(cell->userspacestop)) - (sizeof(cell->userspacestart)))
{
(*old_list)->next = cell;
cell->next = (*list);
break;
}
old_list = list;
(*list) = (*list)->next;
}
}
}

一点解释:我试图保留我在列表中的最后位置,所以我创建了一个“old_list”变量来保留它。起初,我试着看看我是否可以直接在列表的开头插入我的单元格。我不完全确定要放在这里什么,所以我现在发表评论。

然后,如果无法在开头插入它,我将向前移动到我的列表中并尝试插入该元素。 (话又说回来,不确定插入的代码是否正确)

这有什么用吗,还是我对这段代码完全错了?

最佳答案

假设第一个指针指向指向列表的指针,第二个参数是指向要插入的新元素的指针,则没有理由 malloc() 任何东西。您只需要在列表中找到您要插入的位置即可。


struct cell_m {
unsigned int magicnumber ;
struct cell_m *next ;
char *userspacestart ; // character pointers allow pointer arithmetic
char *userspacestop ;
};

// typedefs only exist to confuse you
// typedef struct cell_m *liste_t ;

void insert(struct cell_m **head, struct cell_m *this)
{
for ( ;*head != NULL; head = &(*head)->next) {
if (*head)->userspacestop - (*head)->userspacestart
< this->userspacestop - this->userspacestart) break;

}
this->next = *head;
*head = this;
}

您当然可以使用 void * 指针来做同样的事情,但是您需要大量转换为 char*(或其他粒度)才能使其正常工作.

关于c - 在没有尾部或头的列表中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29341673/

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