Skip to content

Latest commit

 

History

History
81 lines (67 loc) · 2.21 KB

0092. 反转链表 II.md

File metadata and controls

81 lines (67 loc) · 2.21 KB

92. 反转链表 II

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

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/reverse-linked-list-ii

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


一趟扫描

  1. 首先构造一个指向头节点的虚拟头结点,然后依次找到

    • 左节点的前一个节点 beforeL
    • 左节点 lNode
    • 右节点 rNode
    • 右节点的后一个节点 afterR
  2. 在找节点的遍历过程当中,将左节点 lNode 和右节点 rNode 中间的节点反转

  3. 最后

    • 左节点的前一个节点 beforeL -> 右节点 rNode
    • 左节点 lNode -> 右节点的后一个节点 afterR

image

https://leetcode-cn.com/problems/reverse-linked-list-ii/solution/yi-tang-sao-miao-by-cygra-2-dgfw/

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
var reverseBetween = function(head, left, right) {
  if (!head || !head.next || left === right) return head
  var dum = new ListNode(0, head)
  var current = dum
  var beforeL, lNode, rNode, afterR, prev
  var i = 0
  while (i - 1 <= right) {
    if (i + 1 === left) {
      beforeL = current
      current = current.next
    } else if (i === left) {
      lNode = prev = current
      current = current.next
    } else if (i > left && i < right) {
      var next = current.next
      current.next = prev
      prev = current
      current = next
    } else if (i === right) {
      rNode = current
      var next = current.next
      current.next = prev
      current = next
    } else if (i - 1 === right) {
      afterR = current
    } else {
      current = current.next
    }
    i ++
  }
  beforeL.next = rNode
  lNode.next = afterR

  return dum.next
};