天天看點

劍指offer——面試題13:在O(1)時間删除連結清單結點

劍指offer——面試題13:在O(1)時間删除連結清單結點
劍指offer——面試題13:在O(1)時間删除連結清單結點
劍指offer——面試題13:在O(1)時間删除連結清單結點
劍指offer——面試題13:在O(1)時間删除連結清單結點
void DeleteNode(ListNode** pListHead, ListNode* pToBeDeleted)
{
    if(!pListHead || !pToBeDeleted)
        return;

    // 要删除的結點不是尾結點
    if(pToBeDeleted->m_pNext != NULL)
    {
        ListNode* pNext = pToBeDeleted->m_pNext;
        pToBeDeleted->m_nValue = pNext->m_nValue;
        pToBeDeleted->m_pNext = pNext->m_pNext;
 
        delete pNext;
        pNext = NULL;
    }
    // 連結清單隻有一個結點,删除頭結點(也是尾結點)
    else if(*pListHead == pToBeDeleted)
    {
        delete pToBeDeleted;
        pToBeDeleted = NULL;
        *pListHead = NULL;
    }
    // 連結清單中有多個結點,删除尾結點
    else
    {
        ListNode* pNode = *pListHead;
        while(pNode->m_pNext != pToBeDeleted)
        {
            pNode = pNode->m_pNext;            
        }
 
        pNode->m_pNext = NULL;
        delete pToBeDeleted;
        pToBeDeleted = NULL;
    }
}
           
劍指offer——面試題13:在O(1)時間删除連結清單結點