Skip to content

92. Reverse Linked List II

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

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} m
 * @param {number} n
 * @return {ListNode}
 */
var reverseBetween = function(head, m, n) {
  var dummy = new ListNode()
  dummy.next = head
  var tail = dummy

  for (let i = 1; i < m; i++) {
    tail = tail.next
  }

  var revHead = tail.next
  for (let i = m; i < n; i++) {
    let temp = revHead.next
    revHead.next = temp.next
    temp.next = tail.next
    tail.next = temp
  }

  return dummy.next
}
py
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution(object):

    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        tail = dummy = ListNode(None)
        dummy.next = head

        for i in range(1, m):
            tail = tail.next

        revHead = tail.next
        for i in range(m, n):
            temp = revHead.next
            revHead.next = temp.next
            temp.next = tail.next
            tail.next = temp

        return dummy.next