我正在处理链接列表程序,并试图删除最后一个项目。我已经尝试了下面的功能,但是它有问题并导致seg故障。如何删除链接列表中的最后一项?
我有一个结构作为这样一个头文件:
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
}
我我不确定我的意思在这里是否正确,但我需要返回列表的头部,我确信我正在做这件事。任何帮助将非常感激。
请在使用' - >'运算符之前将游标初始化为有效的东西。 “游标”正在被使用未初始化。 – 2015-04-02 11:19:51