• 在链表中找到第一个含有某值的结点并且删除该结点(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;
      }
    }
    测试结果:
  • 相关阅读:
    Linux安装.net core
    在IIS中如何配置SSL(https)
    Lambda的前世今生
    Java建造者模式
    leetcode 83 Remove Duplicates from Sorted List
    【设计】Office
    【设计】简书品牌重构
    【设计总结】
    【交互设计】
    【设计总结】
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13772197.html
Copyright © 2020-2023  润新知