在链表中找到第一个含有某值的结点并且删除该结点(C++|测试用例)

代码:

#include<iostream>
using namespace std;
class listnode{
public:
  int m_nValue;
  listnode* m_pNext;
  listnode(int data):m_pNext(nullptr){
    this->m_nValue = data;
  }
} ;
void removeNode(listnode**pHead,int value)
{
  if(pHead==nullptr||*pHead==nullptr)
  {
    return ;
  }
  listnode* pDeleted = nullptr;
  if((*pHead)->m_nValue==value)
  {
    pDeleted = *pHead;
   *pHead = (*pHead)->m_pNext;
  }
listnode* pnode = *pHead;
while(pnode->m_pNext!=nullptr&&pnode->m_pNext->m_nValue!=value)
{
  pnode = pnode->m_pNext;
}
pDeleted = pnode->m_pNext;
pnode->m_pNext = pnode->m_pNext->m_pNext;
if(pDeleted!=nullptr)
{
  delete pDeleted;
  pDeleted = nullptr;
}
}
int main()
{
  listnode* a = new listnode(1);
  listnode* b = new listnode(2);
  listnode* c = new listnode(3);
  listnode* d = new listnode(4);
  listnode* e = new listnode(5);
  a->m_pNext = b;
  b->m_pNext = c;
  c->m_pNext = d;
  d->m_pNext = e;
  e->m_pNext = nullptr;
  removeNode(&a,2);
  listnode* p = a;
  while(p!=nullptr)
  {
    cout << p->m_nValue << endl;
    p = p->m_pNext;
  }
}
测试结果:

 

 

posted @ 2020-10-06 01:19  诗和远方*  阅读(269)  评论(0编辑  收藏  举报