美文网首页
删除链表的节点

删除链表的节点

作者: gaookey | 来源:发表于2021-11-08 16:33 被阅读0次
    void DeleteNode(ListNode** pListHead, ListNode* pToBeDeleted)
    {
        if(!pListHead || !pToBeDeleted)
            return;
    
        // 要删除的结点不是尾结点
        if(pToBeDeleted->m_pNext != nullptr)
        {
            ListNode* pNext = pToBeDeleted->m_pNext;
            pToBeDeleted->m_nValue = pNext->m_nValue;
            pToBeDeleted->m_pNext = pNext->m_pNext;
     
            delete pNext;
            pNext = nullptr;
        }
        // 链表只有一个结点,删除头结点(也是尾结点)
        else if(*pListHead == pToBeDeleted)
        {
            delete pToBeDeleted;
            pToBeDeleted = nullptr;
            *pListHead = nullptr;
        }
        // 链表中有多个结点,删除尾结点
        else
        {
            ListNode* pNode = *pListHead;
            while(pNode->m_pNext != pToBeDeleted)
            {
                pNode = pNode->m_pNext;
            }
     
            pNode->m_pNext = nullptr;
            delete pToBeDeleted;
            pToBeDeleted = nullptr;
        }
    }
    

    摘抄资料:《剑指offer》

    相关文章

      网友评论

          本文标题:删除链表的节点

          本文链接:https://www.haomeiwen.com/subject/lxauzltx.html