reverseBetween-反转链表
发布日期:2021-05-18 07:53:21 浏览次数:23 分类:精选文章

本文共 1777 字,大约阅读时间需要 5 分钟。

为了解决反转链表中从位置 m 到 n 的部分问题,我们可以使用双指针法,逐步反转子链表并连接到主链表的适当位置。以下是详细的解决步骤和代码实现:

方法思路

  • 找到起点和终点:首先,我们需要找到链表中第 m 个节点作为起点和第 n 个节点作为终点。
  • 反转子链表:使用两个指针,一个从起点开始,另一个从终点开始,逐步将终点前面的节点连接到起点后面,直到连接到起点。
  • 连接前后部分:处理好起点前面的节点和终点后面的节点,将它们连接到反转后的子链表的正确位置。
  • 解决代码

    public class Solution {    public ListNode reverseBetween(ListNode head, int left, int right) {        if (left == right) {            return head;        }        // 找到起点和终点        int count = 0;        ListNode leftNode = null;        ListNode current = head;        while (current != null) {            count++;            if (count == left) {                leftNode = current;            }            current = current.next;        }        count = 0;        current = head;        while (current != null) {            count++;            if (count == right) {                current = current.next;                break;            }            current = current.next;        }        if (leftNode == null || current == null) {            return head;        }        // 反转子链表        // 反转的子链表是从leftNode到current        // 反转的顺序是:从current开始,连接到leftNode,依此类推        ListNode nextRight = current.next;        while (nextRight != null) {            current.next = leftNode;            leftNode = nextRight;            nextRight = leftNode.next;        }        // 处理前后连接        // 如果left >1,连接到左边        if (left > 1) {            if (leftNode.prev != null) {                leftNode.prev.next = leftNode;            } else {                head.next = leftNode;            }        } else {            head = leftNode;        }        // 如果right 

    代码解释

  • 找到起点和终点:使用循环遍历链表,找到第 m 个节点作为起点和第 n 个节点作为终点。
  • 反转子链表:从终点开始,逐步将终点前面的节点连接到起点后面,直到连接到起点,完成子链表的反转。
  • 连接前后部分:处理起点前面的节点和终点后面的节点,确保它们连接到反转后的子链表的正确位置,从而完成整个链表的反转。
  • 这种方法确保了在一次遍历中完成反转,时间复杂度为 O(n),并且只使用常数额外空间。

    上一篇:NestedIterator-扁平化嵌套列表迭代器
    下一篇:spiralOrder-螺旋矩阵

    发表评论

    最新留言

    逛到本站,mark一下
    [***.202.152.39]2025年04月20日 21时57分20秒