栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

文章目录
  • 1. 反转链表(简单)
    • 解法一:递归
    • 解法二:迭代
  • 2. 反转链表前 N 个节点
  • 3. 反转链表前 N 个节点
  • 4. 反转链表 II(中等)

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

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;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/602659.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号