LeetCode热题(JS版)- 92. 反转链表 II

72 阅读1分钟

题目

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

image.png

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

示例 2:

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

提示:

链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n

进阶: 你可以使用一趟扫描完成反转吗?

思路:移动到左侧,对部分链通过pre/curr/next的断链翻转重组实现

这道题目是链表基础题,需要我们将链表从位置 m 到 n 反转,我们可以使用双指针来完成这个过程:

  • 首先,我们需要用一个指针 p 指向链表的头节点,然后用一个指针 pre 来记录需要反转的区间的前驱节点;
  • 接着,我们需要将 p 移动到需要反转的区间的起始节点,pre 移动到 p 的前一个节点;
  • 然后,我们需要使用双指针法来完成区间的反转,具体来说,我们用一个指针 cur 来遍历区间内的每个节点,用一个指针 next 来记录 cur 的后继节点,然后将 cur 的 next 指针指向 pre,然后将 pre 和 cur 分别向后移动一个节点,直到遍历完区间;
  • 最后,我们需要将反转后的区间与链表的其它部分拼接起来,具体来说,我们将 pre 的 next 指针指向反转区间的头节点,反转区间的尾节点的 next 指针指向 cur。
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function reverseBetween(head: ListNode | null, left: number, right: number): ListNode | null {
    // 异常处理
    if(!head) return null;

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

    // 先走到left处
    let pre = dummy;
    for(let i = 0; i < left - 1; i++) pre = pre.next;

    // 取出翻转前的三个元素:pre -> curr -> next
    const curr = pre.next;
    for(let i = left; i < right; i++) {
        const next = curr.next;
        if(!next) continue;
         
        curr.next = next.next;// next断开前面,curr后移:curr -> next => curr -> next.next
        next.next = pre.next;// next翻转:next -> curr
        pre.next = next;// next重接前面,next前移:pre -> next -> curr
    }
    return dummy.next;
};

image.png

总结

  • 时间复杂度 这道题目只需要遍历一遍链表,因此时间复杂度为 O(n),其中 n 是链表的长度。
  • 空间复杂度为 O(1)。

图示:zhuanlan.zhihu.com/p/192900084