面试算法-89-反转链表 II

题目

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

示例 1:
在这里插入图片描述

输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null || head.next == null || left == right) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;

        int count = 1;
        ListNode pre = dummy;
        ListNode cur = head;
        ListNode next = null;

        ListNode p1 = null;
        ListNode p2 = null;
        ListNode p3 = null;
        ListNode p4 = null;
        while (cur != null) {
            next = cur.next;

            if (count == left) {
                p1 = pre;
                p2 = cur;
                pre.next = null;
            }
            if (count == right) {
                p3 = cur;
                p4 = next;
                cur.next = null;
            }
            count++;
            pre = cur;
            cur = next;
        }

        reverse(p2);
        if (p1 != null)
            p1.next = p3;
        p2.next = p4;
        return dummy.next;
    }

    public void reverse(ListNode head) {
        if (head == null || head.next == null) {
            return;
        }

        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;
        while (cur != null) {
            next = cur.next;

            cur.next = pre;

            pre = cur;
            cur = next;
        }
    }
}

相关推荐

  1. 算法题】92. II

    2024-03-24 08:32:03       26 阅读
  2. leetcode 92. II

    2024-03-24 08:32:03       11 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-24 08:32:03       14 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-24 08:32:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-24 08:32:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-24 08:32:03       18 阅读

热门阅读

  1. 区块链与智能合约

    2024-03-24 08:32:03       15 阅读
  2. 机器翻译.

    2024-03-24 08:32:03       16 阅读
  3. 深度学习在遥感图像处理中的应用

    2024-03-24 08:32:03       18 阅读
  4. 从架构角度结合分布式缓存和本地缓存

    2024-03-24 08:32:03       16 阅读
  5. python函数

    2024-03-24 08:32:03       18 阅读
  6. 继承和深拷贝封装

    2024-03-24 08:32:03       18 阅读
  7. 大模型: 提示词工程(prompt engineering)

    2024-03-24 08:32:03       17 阅读
  8. JVM学习

    JVM学习

    2024-03-24 08:32:03      16 阅读
  9. 【测试思考】设计测试用例时,你在想什么

    2024-03-24 08:32:03       15 阅读
  10. Electron IPC通信机制深度解析与实例演示

    2024-03-24 08:32:03       15 阅读
  11. 如何系统地自学 Python?

    2024-03-24 08:32:03       14 阅读
  12. 学习资料记录

    2024-03-24 08:32:03       15 阅读
  13. 20 有效的括号

    2024-03-24 08:32:03       17 阅读
  14. 机器翻译评价指标 BLEU分数

    2024-03-24 08:32:03       20 阅读