2015-04-01 74 views
0

我正在处理链接列表程序,并试图删除最后一个项目。我已经尝试了下面的功能,但是它有问题并导致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 
} 

我我不确定我的意思在这里是否正确,但我需要返回列表的头部,我确信我正在做这件事。任何帮助将非常感激。

+0

请在使用' - >'运算符之前将游标初始化为有效的东西。 “游标”正在被使用未初始化。 – 2015-04-02 11:19:51

回答

1
  1. 您没有初始化cursor
  2. 不要泄漏您删除的节点。在这里可能应该有一个free()电话。
  3. 想想你需要返回什么,如果你的列表只有一个条目。
+0

我需要设置父项等于当前元素(即光标),要做到这一点,然后我会简单地初始化光标在程序的开始cursor = head? – user3739406 2015-04-01 23:15:25

+0

另外,你定义了一个类型“struct test”,但是你的函数需要一个类型“test”。这些不一定是相同的类型。 “测试”在哪里定义? – 2015-04-01 23:32:08