struct TList//链表节点的结构
{
int m_nData;
TList * m_pNext;
};
int AddNode(TList ** pList)//向链表添加节点
{
if( pList == NULL )
return 0;
int n = 0;
TList *pHead = *pList;
for( int i = 0; i < 1000; ++i )
{
TList * pNode = new TList;
pNode->m_nData = i + 1;
pNode->m_pNext = pHead;
pHead = pNode;
++n;
}
*pList = pHead;
return n;
}
int ListCount(const TList * pListHead)//计算链表节点的个数
{
int n = 0;
while( pListHead != NULL )
{
++n;
pListHead = pListHead->m_pNext;
}
return n;
}
int DisplayList(const TList * pListHead)//遍历显示链表节点数据
{
int n = 0;
while( pListHead != NULL )
{
++n;
cout << pListHead->m_nData << " ";
if( n % 10 == 0 )
cout << endl;
pListHead = pListHead->m_pNext;
}
return n;
}
int ReMoveNode(TList ** pListHead)//删除链表的部分节点
{
if( *pListHead == NULL || pListHead == NULL )
return 0;
int n = 0;
TList *pFront = (*pListHead);
TList *pCurrent = pFront->m_pNext;
while( pCurrent != NULL ) //从第二个节点开始判断是否要删除
{
if( pCurrent->m_nData % 2 == 0 ) //删除该节点
{
pFront->m_pNext = pCurrent->m_pNext;
delete pCurrent;
pCurrent = pFront->m_pNext;
++n;
}
else
{
pFront = pCurrent;
pCurrent = pCurrent->m_pNext;
}
}
TList *pHead = (*pListHead);
if( pHead->m_nData % 2 == 0 ) //检查头节点
{
*pListHead = pHead->m_pNext;
delete pHead;
++n;
}
return n;
}
int DeleteAll(TList **pList)
{
if( pList == NULL )
return 0;
int n = 0;
TList *pHead = *pList, *pNext;
while( pHead != NULL )
{
++n;
pNext = pHead->m_pNext;
delete pHead;
pHead = pNext;
}
*pList = NULL;
return n;
}
int main()//测试
{
TList * pList = NULL;
AddNode(&pList);
cout << "list count: " << ListCount(pList) << endl;
cout << "remove list count: " << ReMoveNode(&pList) << endl;
cout << "list count: " << ListCount(pList) << endl;
cout << "remove all list count: " << DeleteAll(&pList) << endl;
cout << "list count: " << ListCount(pList) << endl;
return 0;
}