206. 反转链表
- 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
题解(双指针法):
/**
1. Definition for singly-linked list.
2. public class ListNode {
3. int val;
4. ListNode next;
5. ListNode() {}
6. ListNode(int val) { this.val = val; }
7. ListNode(int val, ListNode next) { this.val = val; this.next = next; }
8. }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
ListNode temp = null;
while (cur != null) {
temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
}
分析:
- 暂存下一节点
- 反转当前节点
- 更新prev指针和当前节点
- 重复以上步骤
=========================================
题解(递归法):
/**
1. Definition for singly-linked list.
2. public class ListNode {
3. int val;
4. ListNode next;
5. ListNode() {}
6. ListNode(int val) { this.val = val; }
7. ListNode(int val, ListNode next) { this.val = val; this.next = next; }
8. }
*/
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(null, head);
}
public ListNode reverse(ListNode pre, ListNode cur) {
if (cur == null) {
return pre;
}
ListNode temp = cur.next;
cur.next = pre;
return reverse(cur, temp);
}
}
分析:
- 递归出口:访问到最后一个节点时,即cur == null
- 暂存下一节点
- 反转当前节点
- 递归调用继续反转下一节点
注意:这里的递归过程类似于双指针法里的循环过程