LeetCode第92题反转链表 II

继续打卡算法题,今天学习的是LeetCode第92题反转链表 II,这道题目是道中等题。算法题的一些解题思路和技巧真的非常巧妙,每天看一看算法题和解题思路,我相信对我们的编码思维和编码能力有一些提升。

分析一波题目

本题是反转链表的升级版本,本题需要反转指定位置区间的链表段,我们只需要记录一下反转链表段的头部和尾部,还有前一个指针和后一个指针,等反转结束后将记录的重新指向反转后的指向即可。

这种做法比较容易理解。通过4个指针记录了反转链表关键的位置。

本题解题技巧

1、通过4个指针记录反转链表的头,尾,和前序和后继节点,代码实现比较好理解。

编码解决

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {

        if(left == right) {
            return head;
        }

        //虚拟头节点
        ListNode dumy = new ListNode();
        dumy.next = head;

        //记录待反转的前一个节点指针。
        ListNode pre = null;
        ListNode next = null;

        ListNode pre1 = null;

        //记录反转链表的头尾节点
        ListNode start = null;
        ListNode end = null;

        int index = 0;

        //遍历到的节点
        ListNode curr = dumy;
        while(curr != null) {
           // System.out.println(curr.val);
            ListNode temp =  curr.next;
            if(index == left-1) {
                pre = curr;
            }

            if(index == left) {
                start = curr;
            }

            if(index == right) {
                end = curr;
                
            }

            if(index == right + 1) {
                next = curr;
                
            }

            //开始反转
            if(index > left && index <= right) {
                //System.out.println(curr.val);
               curr.next = pre1;
               
            }

            //反转完成的时候
            if(index == right || index > right) {
                pre.next = end;
                //System.out.println(next);
                start.next = next;
            }

            pre1 = curr;
            curr = temp;

            index ++;
            System.out.println("index"+index);

        }

        return dumy.next;
    }
}

总结

1、反转链表题目,本身不难理解,但是代码实现层面需要更新节点指向,这个在编码过程中是比较难控制的。

相关推荐
ai小鬼头14 分钟前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
Touper.20 分钟前
SpringBoot -- 自动配置原理
java·spring boot·后端
Alfred king23 分钟前
面试150 生命游戏
leetcode·游戏·面试·数组
水木兰亭42 分钟前
数据结构之——树及树的存储
数据结构·c++·学习·算法
一只叫煤球的猫1 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
一只鹿鹿鹿1 小时前
信息化项目验收,软件工程评审和检查表单
大数据·人工智能·后端·智慧城市·软件工程
专注VB编程开发20年1 小时前
开机自动后台运行,在Windows服务中托管ASP.NET Core
windows·后端·asp.net
程序员岳焱1 小时前
Java 与 MySQL 性能优化:MySQL全文检索查询优化实践
后端·mysql·性能优化
Jess072 小时前
插入排序的简单介绍
数据结构·算法·排序算法
老一岁2 小时前
选择排序算法详解
数据结构·算法·排序算法