【发布时间】:2015-04-01 23:07:35
【问题描述】:
我正在开发一个链表程序,并试图删除最后一项。我尝试了下面的功能,但它有问题并导致了段错误。
我在头文件中有一个这样的结构:
struct test{
char * name;
char * type;
struct test * next;
};
我在单独的 .c 文件中有一个函数,如下所示:
//NOTE Correct memory is allocated in other parts of the program
//(i.e not in this function)
//Also values are initialized in other functions...etc
test * removeLastItem(test * head)
{
test * parent, * cursor;
if(head == NULL) //if list is empty return NULL
{
return NULL;
}
else
{
while(cursor->next != NULL) //untill last item of the list is found..
{
parent = cursor; //parent equal to current element
cursor = cursor->next; //current element set to next pointer of current element
}
parent->next = NULL; //parent next pointer is now null
}
return head; //return the head of the list
}
我不确定我的暗示是否正确,但我需要返回列表的头部,我相信我正在这样做。任何帮助将不胜感激。
【问题讨论】:
-
请在使用
->运算符之前将光标初始化为有效的值。cursor未初始化使用。
标签: c pointers data-structures linked-list