删除单向链表的部分节点

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值