/*
* 释放单向循环链表中的全部元素,并将链表头指针设置为空。
* 使用局部变量cur,nxt。
* 下面的程序中存在内存泄露 想以一种简洁的方式进行更正,但是目前还
* 没有想到。
*/
void free(struct node* &head)
{
if (NULL == head)
return;
struct node *cur, *nxt;
cur = head; nxt = head->next;
/* 使用do-while不好 */
while (nxt != head)
{
delete cur;
cur = nxt;
nxt = nxt->next;
}
head = NULL;
}
示例代码:
void free_cylicList(node * &head)
{
if (!head) return ;
node *p1, *p2, *cur;
p1 = p2 = head;
for (p2 = p2->next; p2 != p1; cur = p2, p2 = p2->next, delete cur);
delete p2;
head = NULL;
}