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

相关推荐
Jacob02344 分钟前
Node.js 性能瓶颈与 Rust + WebAssembly 实战探索
后端·rust·node.js
王中阳Go13 分钟前
分库分表之后如何使用?面试可以参考这些话术
后端·面试
知其然亦知其所以然19 分钟前
ChatGPT太贵?教你用Spring AI在本地白嫖聊天模型!
后端·spring·ai编程
技术炼丹人21 分钟前
从RNN为什么长依赖遗忘到注意力机制的解决方案以及并行
人工智能·python·算法
NfN-sh40 分钟前
计数组合学7.12( RSK算法的一些推论)
笔记·学习·算法
ikkkkkkkl1 小时前
LeetCode:15.三数之和&&18.四数之和
c++·算法·leetcode
kinlon.liu1 小时前
内网穿透 FRP 配置指南
后端·frp·内网穿透
kfyty7251 小时前
loveqq-mvc 再进化,又一款分布式网关框架可用
java·后端
Dcr_stephen1 小时前
Spring 事务中的 beforeCommit 是业务救星还是地雷?
后端
raoxiaoya1 小时前
Golang中的`io.Copy()`使用场景
开发语言·后端·golang