在C中弹出一个空链表
所以我的目标是删除一个链表头节点。但当我有一个空的列表时,我很难做到这一点,这就是我目前所拥有的在C中弹出一个空链表,c,linked-list,C,Linked List,所以我的目标是删除一个链表头节点。但当我有一个空的列表时,我很难做到这一点,这就是我目前所拥有的 conscell *ll_pop(conscell *list) { if ( list == NULL) { // do nothing return list; } if ( list != NULL) { conscell *p = list->next; free(list);
conscell *ll_pop(conscell *list)
{
if ( list == NULL) { // do nothing
return list;
}
if ( list != NULL) {
conscell *p = list->next;
free(list);
list = p;
return list;
}
下面是实现。我们做了一系列的流行音乐。首先我们弹出两个节点,然后弹出3个节点
conscell *ll_push(conscell *list, void *data)
{
conscell *new = xmalloc(sizeof *new); // allocate associate memory
new->data = data; // assign data
new->next = list; // attach the new node to the old list
return new;
}
如何定义空列表?在调用函数之前,在main中将列表设置为
NULL
,它应该可以工作。您需要做的是使用pop的返回值来修改列表指针
你的主屏幕应该是这样的
int main(void)
{
conscell *list= NULL;
....
list = ll_push(list,data1);
list = ll_push(list,data2);
list = ll_push(list,data3);
list = ll_push(list,data4);
list = ll_pop(list);
list = ll_pop(list);
list = ll_pop(list);
list = ll_pop(list);
list = ll_pop(list);
}
第四个pop会将列表指针分配回NULL,第五个pop和其他pop会正常返回。您面临什么问题???因此,我创建了一个包含4个节点的测试文件,并弹出了5次,但它给了我消息分段错误@avinashpandey您是否确保最后一项的next为NULL?事实上,让我们看看你的push是的,请显示push代码以及调用它的主函数。这就是我如何定义空列表conscell*list=NULL;因此,我创建了一个包含4个节点的测试文件,并弹出了5次,但如果整个列表为
NULL
,则会出现消息分段错误@user3711622。如果列表的开头为NULL
,则不应该有任何节点。@TimothyBrown如果列表的开头为NULL
,则问题似乎不在这些函数中,但可能在您使用它们的方式中。显示其余的代码。