C链表清除功能

时间:2012-06-23 15:41:43

标签: 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指向的内存”这些词语没有帮助。

由于

1 个答案:

答案 0 :(得分:1)

不是测试所有不同的特殊情况,而是可以使用指向列表元素指针的指针,因为无论如何你都要遍历列表,跟踪最后看到的元素:

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所有元素,但您可以轻松修改它以删除第一个元素以匹配data