1、非递归版
三指针,保留当前的下一个节点,将当前节点的m_Next指向前一个节点,前一个节点移动到当前节点,当前节点移动到下一个节点
#include<iostream>
struct listNode
{
int m_nValue;
listNode* m_Next;
listNode(int _value):m_nValue(_value){}
};
listNode* ReverseList(listNode* pHead)
{
listNode* pReverseHead = nullptr;
listNode* pNode = pHead;
listNode* pPre = nullptr;
while (pNode)
{
listNode* pNext = pNode->m_Next;
if (pNext == nullptr)
pReverseHead = pNode;
pNode->m_Next = pPre;
pPre = pNode;
pNode = pNext;
}
return pReverseHead;
}
2、递归版
m_ListNode* ListOfSingle::ReverseList(m_ListNode* pHead)
{
if (pHead == nullptr || pHead->next == nullptr)
return pHead;//找到最后一个节点,作为结束条件
m_ListNode* newHead = ReverseList(pHead->next);//最后一个节点为新得头节点
pHead->next->next = pHead;//当前节点的下一个节点指向当前节点
pHead = nullptr;//当前节点为空
return newHead;//返回新头节点
}