题目13 在O(1)时间删除链表节点

/////////////////////////////////////////////////////////////////////////////////////
// 3. 题目13 在O(1)时间删除链表节点
// 平均时间复杂度:[(n-1)*O(1) + O(n)] / n ---> O(1)

void DeleteListNode(ListNode<int>** ppNode, ListNode<int>* pDelNode)
{
    if (NULL == ppNode)
    {
        return;
    }

    // 1.如果不是尾节点
    if (pDelNode->m_pNextNode != NULL)
    {
        ListNode<int>* pNext = pDelNode->m_pNextNode;
        pDelNode->m_stData = pNext->m_stData;
        pDelNode->m_pNextNode = pNext->m_pNextNode;

        delete pNext;
        pNext = NULL;
    }
    // 2. 链表只有一个节点
    else if (*ppNode == pDelNode)
    {
        delete pDelNode;
        pDelNode = NULL;
        *ppNode = NULL;
    }
    //链表中有多个节点,删除尾节点
    else
    {
        // 这里时间复杂度O(n)
        ListNode<int>* pNode = *ppNode;
        while (pNode->m_pNextNode != pDelNode)
        {
            pNode = pNode->m_pNextNode;
        }

        pNode->m_pNextNode = NULL;
        delete pDelNode;
        pDelNode = NULL;
    }

}

void DeleteNode(CSingleList<int>* pList, int iDelValue)
{
    ListNode<int>* pNode = pList->GetHeadNode();
    ListNode<int>* pDelNode = pList->Find(pList->GetHeadNode(), iDelValue);
    if (pDelNode && pNode)
    {
        // 删除节点
        DeleteListNode(&pNode, pDelNode);
        pList->Traversal();
    }
}

void DeleteNodeTestFunc()
{
    cout << "\n\n --------------- DeleteNodeTestFunc Start -------------->" << endl;
    int aiArray[] = {12, 14, 3, 67, 8, 65, 45, 67, 85, 45};
    int iLen = sizeof(aiArray) / sizeof(int);

    CSingleList<int>* pList = new CSingleList<int>();
    if (!pList)
    {
        return;
    }

    // 构建链表
    for (int i = 0; i < iLen; i++)
    {
        pList->Insert(aiArray[i]);  // 头插法
    }

    pList->Traversal();

    int iDelVal = aiArray[iLen - 1];
    cout << "1.删除头结点: " << iDelVal << endl;
    DeleteNode(pList, iDelVal);

    iDelVal = aiArray[4];
    cout << "2.删除中间节点: " << iDelVal << endl;
    DeleteNode(pList, iDelVal);

    iDelVal = aiArray[0];
    cout << "3.删除尾节点: " << iDelVal << endl;
    DeleteNode(pList, iDelVal);

    // 释放内存
    SAVE_DELETE(pList);

    cout << "\n\n --------------- DeleteNodeTestFunc End -------------->" << endl;

}
posted @ 2019-07-28 13:35  VIP丶可乐  阅读(103)  评论(0编辑  收藏  举报