使用的链表相关定义及函数在:链表最小结构(C++版本)
循环实现:
void ReverseList(MyList& myList)
{
if (nullptr == myList.pHead) return;
ListNode* pCurNode = myList.pHead;
ListNode* pNextNode = nullptr;
ListNode* pPrevNode = nullptr;
while (pCurNode->pNext != nullptr)
{
pNextNode = pCurNode->pNext;
pCurNode->pNext = pPrevNode;
pPrevNode = pCurNode;
pCurNode = pNextNode;
}
pCurNode->pNext = pPrevNode;
myList.pHead = pCurNode;
}
递归实现:
ListNode* ReverseList(ListNode* pPrevNode, ListNode* pCurNode)
{
if (nullptr == pCurNode) return pPrevNode;
ListNode* pNextNode = pCurNode->pNext;
pCurNode->pNext = pPrevNode;
return ReverseList(pCurNode, pNextNode);
}
void ReverseList(MyList& myList)
{
myList.pHead = ReverseList(nullptr, myList.pHead);
}