链表的销毁和清空c++程序

*******************************************
//链表的销毁
void ClearLinkList(LinkNode **pHead) //传入为二级指针,否则不能将其他节点置为nullptr
{
if(*pHead == nullptr) //判断是否为空链表
{
cout<<"This is an empty LinkList"< return;
}
LinkNode *pTemNode = nullptr;
while((*pHead)->pNext) //这种情况下,包含了只有头节点的情况;
{ //不只含有头节点时,最后*pHead指到最后的一个元素;
pTemNode = (*pHead)->pNext;
delete *pHead;
*pHead = pTemNode;
}
if((*pHead) != nullptr) //将只有一个头节点或者最后一个节点销毁
{
delete *pHead;
pHead = nullptr;
}
cout<<"Now LinkList has been cleared!"<}
********************************************
//链表的清空
void DestoryLinkList(LinkNode **pHead)
{
if(*pHead == nullptr)
{
cout<<"This is an empty LinkList!"< return;
}
if((*pHead)->pNext == nullptr) //相比链表销毁,多一步判断是否只有头节点这种情况
{ //这种情况下,直接返回,不做处理
cout<<"The LinkList is originally empty!"< return;
}
while((*pHead)->pNext)
{
LinkNode *pTemNode = (*pHead)->pNext;
delete *pHead;
*pHead = pTemNode;
}
if((*pHead))
{
delete *pHead;
*pHead = nullptr;
}
cout<<"Now The LinkList has been cleared!"<}

你可能感兴趣的:(数据结构和算法)