迭代法思路
- 定义两个指针: pre 和 cur;pre 在右 cur 在左,初始cur指向NULL,pre指向第一个结点
- 每次让 pre 的 next指向 cur ,实现一次局部反转
- 局部反转完成之后, pre 和 cur同时往前移动一个位置,
- 循环上述过程,直至 pre到达链表尾部
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre=NULL;
ListNode* cur = head;
while(cur!=NULL)
{
ListNode* after = cur->next;
cur->next = pre;
pre = cur;
cur = after;
}
return pre;
}
};
递归反转链表
迭代的思想比较直观,那么递归如何理解呢? 同时,这也是递归的核心。
我们要知道函数是要干嘛的:
输入一个节点 head ,将head为头的链表反转,并返回反转之后的头结点。
结合函数定义,看着上面的图(图来自labuladong算法笔记),可以reverseList(head.next) 就相当于把除第一个结点之外的剩余链表反转并得到头节点,此时就剩第一个结点没反转了,执行
head.next.next = head;
head.next = null;
结合前面分析,上面两行代码自己意会应该问题不大啦
Java实现
class Solution {
public ListNode reverseList(ListNode head) {
// 递归终止条件
if(head == null || head.next == null)
{
return head;
}
ListNode r = reverseList(head.next);
head.next.next = head;
head.next = null;
return r;
}
}
C++实现
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
ListNode* res = new ListNode();
res->next = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return res->next;
}
};