1. 反转链表(简单)
题目描述:递归 迭代 反转整个链表
地址: https://leetcode-cn.com/problems/reverse-linked-list/
2021/11/25
解法一:递归
做题反思:基线条件写的有误 -> 导致只有一个结点以及空链表时出现空指针异常
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
}
解法二:迭代
https://labuladong.gitee.io/algo/2/17/18/
AC
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head, nxt = head;
while (cur != null) {
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
}
2. 反转链表前 N 个节点
题目描述:将链表的前 n 个节点反转(n <= 链表长度)ListNode reverseN(ListNode head, int n)
地址: https://labuladong.gitee.io/algo/2/17/17/
2021/11/25
做题反思:
- 学习技巧 -> 引入后驱节点
- 想好基线条件
ListNode successor = null;
public ListNode reverseN(ListNode head, int n) {
if (n == 1) {
successor == head.next;
return head;
}
ListNode last = reverseN(head.next, n - 1);
head.next.next = head;
head.next = successor;
return last;
}
3. 反转链表前 N 个节点
题目描述:「反转以 a 为头结点的链表」其实就是「反转 a 到 null 之间的结点」,那么如果让你「反转 a 到 b 之间的结点」你会不会?ListNode reverse(ListNode a, ListNode b)
地址: https://labuladong.gitee.io/algo/2/17/18/
2021/11/25
/** 反转区间 [a, b) 的元素,注意是左闭右开 */
AC
class Solution {
public ListNode reverseList(ListNode a, ListNode b) {
ListNode pre = null, cur = a, nxt = a;
while (cur != b) {
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
}
4. 反转链表 II(中等)
题目描述:反转链表的一部分 -> 给一个索引区间 [m,n](索引从 1 开始),仅仅反转区间中的链表元素
地址: https://leetcode-cn.com/problems/reverse-linked-list-ii/
2021/11/25
做题反思:反转前 N 个结点需要熟练
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if (left == 1) {
return reverseN(head, right);
}
head.next = reverseBetween(head.next, left -1, right -1);
return head;
}
ListNode successor = null;
ListNode reverseN(ListNode head, int n) {
if (n == 1) {
successor = head.next;
return head;
}
ListNode last = reverseN(head.next, n - 1);
head.next.next = head;
head.next = successor;
return last;
}
}