删除链表的最后一个节点 - 可能是错误的实现?

时间:2014-08-12 18:31:52

标签: c linked-list

我遇到了this网站,其中使用以下代码删除了链接列表的最后一个节点:

int remove_last(node_t * head) {
    int retval = 0;
    /* if there is only one item in the list, remove it */
    if (head->next == NULL) {
        head->val
        free(head);
        head = NULL;
        return retval;
    }

    node_t * current = head;

    while (current->next->next != NULL) {
        current = current->next;
    }
}

我的问题很简单,这个例子不是错了吗?我的意思是,只有当只有一个节点时才会释放节点的内存。在任何其他情况下,它并没有真正做某事,只是继续前往while (current->next->next != NULL)循环中的下一个节点。我没注意到什么吗?

2 个答案:

答案 0 :(得分:1)

你是对的。方法错了。而且head本身可以等于NULL,所以甚至是方法的第一个可执行语句

if (head->next == NULL) {

会导致程序异常终止。

在此声明下面有语法错误

if (head->next == NULL) {
    head->val
    free(head);

因此代码不会被编译。

答案 1 :(得分:1)

你可以尝试这个:

int remove_last(node_t * head)
{
    int retval = 0;
    /* if there is only one item in the list, remove it */
    if (head->next == NULL) 
    {
        retval = head->val;
        free(head);
        head = NULL;
        return retval;
    }
    /*if there are another items */
    else
    {
        node_t * current = head;
        while (current->next->next != NULL) 
            current = current->next;
        retval = current->val;
        free(current->next);
        current->next = NULL;
    }
    return retval;
}
相关问题