我已经声明了如下结构:
struct example
{
// some element here
struct example *next;
};
struct example *head;
假设我已经从“ example”结构中创建了一个队列,现在我想移出head元素(当然,移出队列中的第一个元素后,我必须将其从队列中删除)。我有这样的删除代码:
void delete()
{
struct example *temp = malloc (sizeof(struct example) * 1);
temp = head;
head = head->next;
free(temp);
}
我的问题是函数“删除”完成工作:
删除队列中的第一个元素并使下一个元素成为新队列的头
或2.不是删除队列中的第一个元素,而是使head = head-> next并删除“ temp”指针和“ the old head”仍然存在
最佳答案
实际上,您正在将head
设置为队列中的下一项,并删除旧的标题。但是,出于某种原因,您正在使用malloc()
创建内存,然后在下一行覆盖temp
时丢失了唯一的指针。您应该将temp
初始化为head
。 malloc()
函数中无需delete()
内存。如果确实需要malloc()
,请注意* 1
是多余且不必要的。
另外,如果您的队列为空并且head
为NULL
会发生什么?考虑一下。
您的队列是否正常工作还有待观察,因为您还需要tail
指针来知道将新项目添加到队列的位置。
另外,我将避免命名函数delete()
,因为它可能与C ++关键字delete
混淆。 remove()
更合适。
关于c - 从队列中删除头元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23683651/