[英]C linked-list remove function
這是我的鏈表的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
匹配的元素,但是您可以輕松地對其進行修改,以刪除第一個與data
匹配的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.