题目16 反转链表

/////////////////////////////////////////////////////////////////////////////////////
// 6. 题目16 反转链表
//时间复杂度:O(n), 空间复杂度:O(1)

ListNode<int>* ReverseList(ListNode<int>* pHead)
{
    if (NULL == pHead)
    {
        return NULL;
    }

    ListNode<int>* pNode = pHead;
    ListNode<int>* pReverseHead = NULL;
    ListNode<int>* pPreNode = NULL;

    while (pNode)
    {
        // 1.先保存下一个节点
        ListNode<int>* pNextNode = pNode->m_pNextNode;
        if (NULL == pNextNode)
        {
            //最后一个节点,作为反转链表的头结点
            pReverseHead = pNode;
        }

        // 2.改变节点指向
        pNode->m_pNextNode = pPreNode;
        pPreNode = pNode;
        pNode = pNextNode;
    }

    return pReverseHead;
}

void TraversalList(ListNode<int>* pNode)
{
    while (pNode)
    {
        if (!pNode->m_pNextNode)
        {
            printf("%02d", pNode->m_stData);
        }
        else
        {
            printf("%02d -> ", pNode->m_stData);
        }
        pNode = pNode->m_pNextNode;
    }

    putchar(10);
}

void ReverseListTestFunc()
{
    cout << "\n\n --------------- ReverseListTestFunc Start -------------->" << endl;
    int aiArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
    int iLen = sizeof(aiArray) / sizeof(int);
    TRAVERSAL_ARRAY(aiArray, iLen);

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

    for (int i = 0; i < iLen; i++)
    {
        pList->Insert(aiArray[i]);
    }
    pList->Traversal();

    // 反转链表
    ListNode<int>* pNode = pList->GetHeadNode();
    ListNode<int>* pReverseNode = ReverseList(pNode);
    if (pReverseNode)
    {
        cout << "链表反转后: " << endl;
        TraversalList(pReverseNode);
    }

    // 释放内存
    SAVE_DELETE(pList);

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

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