【问题标题】:How to remove the last item in a linked list?如何删除链表中的最后一项?
【发布时间】: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


【解决方案1】:
  1. 您没有初始化cursor
  2. 不要泄露您删除的节点。这里应该有一个free() 电话。
  3. 考虑一下如果您的列表只有一个条目,您需要返回什么。

【讨论】:

  • 我需要将 parent 设置为等于当前元素(即光标),为此,我是否只需在程序开头通过 cursor = head 初始化光标?
  • 另外,您定义了“struct test”类型,但您的函数采用“test”类型。这些不一定是同一类型。 “测试”在哪里定义?
猜你喜欢
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
  • 2016-09-10
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
相关资源
最近更新 更多