力扣算法 Java 刷题笔记【链表篇】hot100(二)递归反转链表的一部分 4

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
做题反思:

  1. 学习技巧 -> 引入后驱节点
  2. 想好基线条件
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;
    }
}

在这里插入图片描述

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心海非海_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值