迭代方式
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *pre = nullptr;
ListNode *cur = pHead;
ListNode *nex = nullptr;
while (cur)
{
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
return pre;
}
};
递归方式
思路
1.拆解为两个子问题,即头节点和除头节点之外的所有节点
2.子问题解决方式和总问题一样
3.存在最小子问题
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead == NULL || pHead->next == NULL)return pHead;
ListNode* p = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = nullptr;
return p;
}
};