C 链表删除函数

标签 c linked-list free

这是我的链表的remove()函数。如何才能更好,为什么?

void removeData(void *data, struct accList *theList)
{
  if(theList->head == NULL)                  //nothing can be deleted
    return;
  else if(theList->head == theList->tail)          //there is only one element in the    list
  {
    free(theList->head);
    theList->head = theList->tail = NULL;
  }
  else if(data == theList->head->data)           //the node to be deleted is the head
  {
    struct accListNode *temp = theList->head;
    free(theList->head);
    theList->head = temp;
    theList->head->next = temp->next;
  }
  else if(data == theList->tail->data)      //the node to be deleted is the tail
  {
    struct accListNode *cur;
    for(cur = theList->head; cur->next->next != NULL; cur = cur->next);
    theList->tail = cur;
    free(cur->next);
    cur->next = NULL;
  }
  else                                     //the node to be deleted is any other node
  {
    struct accListNode *cur;
    for(cur = theList->head; cur != NULL; cur = cur->next)
    {  
      if(cur->data == data)     //this is the node we must delete from theList
      {
        struct accListNode *temp = cur->next->next;
        free(cur->next);
        cur->next = temp;
        break;
      }
    }
  }
}

另外,有人能给我详细解释一下 free() 函数吗? “释放 ptr 指向的内存”这句话没有帮助。

谢谢

最佳答案

您可以使用指向列表元素指针的指针,而不是测试所有不同的特殊情况,并且由于您无论如何都在遍历列表,因此可以跟踪看到的最后一个元素:

void removeData ( void *data , struct accList *theList ) {
    struct acclist *last = NULL, **finger = &theList->head;
    while ( *finger != NULL ) {
        if ( (*finger)->data == data )
            *finger = (*finger)->next;
        else {
            last = *finger;
            finger = &( (*finger)->next );
            }
        }
    theList->last = last;
    }

此代码与您的函数的不同之处在于,它删除与 data 匹配的所有元素,但您可以轻松修改它以删除第一个匹配数据的元素。

关于C 链表删除函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11170795/

相关文章:

c - 如何以编程方式更改串行 COM 端口号?

java - 为什么在这个树遍历中只有 log(N) 次递归调用?

c - 如何使用具有多个变量的结构初始化链表

c++ - 使用自定义 TCL 解释器获取 "free(): invalid pointer"

c - 从内核列表中删除元素

c - 删除基于结构的数组中的最后一个单元格

c - 写入和读取文件时出现 SIGSEGV 错误

比较两个内存地址并显示它们相等

C链表,丢失元素

c - C 中具有负索引的二维数组