【链表】反转

代码如下:

TestPointer.h

struct ListNode
{
    int m_nValue;
    ListNode *m_pNext;
};

    
class TestPointer
{
public:
    ListNode* reverseListNode(ListNode *pHead);

private: ListNode* reverseCode(ListNode *pNode); };

TestPointer.cpp

ListNode* TestPointer::reverseListNode(ListNode *pHead)
{
    if (pHead == nullptr)
        return nullptr;

    ListNode *pReverseHead = nullptr;
    pReverseHead = reverseCode(pHead);
    return pReverseHead;
}

ListNode * TestPointer::reverseCode(ListNode *pNode)
{
    if (pNode->m_pNext == nullptr)
        return pNode;

    ListNode *pReverseHead= reverseCode(pNode->m_pNext);
    ListNode *pCurNode= pReverseHead;
    while(pCurNode->m_pNext != nullptr)
    {
        pCurNode = pCurNode->m_pNext;
    }

    pCurNode->m_pNext = pNode;
    pNode->m_pNext = nullptr;

    return pReverseHead;

}

 

留意:在链表反转时,链表尾结点需要指向nullptr

评点:虽然递归实现的可读性好,但是效率比较差

扩展:可以考虑不用递归实现反转链表的功能

 

posted @ 2018-06-28 14:22  绍荣  阅读(167)  评论(0编辑  收藏  举报