刷题练习
反转链表
输入链表为:1->2->3->4->5->6
输出链表为:6->5->4->3->2->1
本题提供了两种解决问题的思路,常规解决方法和递归解决方法
//
// main.cpp
// ConsoleApp
//
// Created by Xming on 2022/2/24.
//
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
int m_nValue;
Node* m_pNext;
Node(int nValue, Node* pNext = nullptr) : m_nValue(nValue), m_pNext(pNext)
{
}
};
class Solution
{
public:
/**
*@brief 反转链表(常规思路)
*/
static Node* ReverseList(Node* pHead)
{
Node* pPre = nullptr;
Node* pCur = pHead;
while (nullptr != pCur)
{
Node* pNext = pCur->m_pNext;
pCur->m_pNext = pPre;
pPre = pCur;
pCur = pNext;
}
return pPre;
}
/**
*@brief 反转链表(递归思路)
*/
static Node* ReverseListByRecursion(Node* pHead)
{
return ReverseListByRecursion(nullptr, pHead);
}
static Node* ReverseListByRecursion(Node* pPre, Node* pCur)
{
if (nullptr == pCur)
return pPre;
Node* pNext = pCur->m_pNext;
pCur->m_pNext = pPre;
return ReverseListByRecursion(pCur, pNext);
}
// 创建链表
static Node* CreateList(const vector<int>& vecData)
{
if (vecData.empty())
return nullptr;
Node* pHead = new Node(vecData[0]);
Node* pCur = pHead;
for(size_t i = 1; i < vecData.size(); ++i)
{
pCur->m_pNext = new Node(vecData[i]);
pCur = pCur->m_pNext;
}
return pHead;
}
// 打印输出链表
static void PrintList(Node* pHead)
{
Node* pCur = pHead;
cout << "List Data:[ ";
while (nullptr != pCur)
{
if (nullptr != pCur->m_pNext)
{
cout << pCur->m_nValue << ", ";
}
else
{
cout << pCur->m_nValue << " ]\n";
return;
}
pCur = pCur->m_pNext;
}
cout << " ]\n";
}
// 测试函数
static void Test()
{
vector<int> vecData = { 6, 5, 4, 3, 2, 1 };
Node* pHead = CreateList(vecData);
PrintList(pHead);
// 测试常规反转
pHead = ReverseList(pHead);
PrintList(pHead);
// 测试递归反转
pHead = ReverseListByRecursion(pHead);
PrintList(pHead);
}
};
int main(int argc, const char * argv[]) {
Solution::Test();
return 0;
}