【发布时间】:2012-06-23 15:41:43
【问题描述】:
这是我的链表 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 指向的内存”这句话没有帮助。
谢谢
【问题讨论】:
-
“如何改进此代码?”形式的问题应该在codereview.stackexchange.com。
标签: c linked-list free