Skip to content

Latest commit

 

History

History
35 lines (32 loc) · 810 Bytes

092.md

File metadata and controls

35 lines (32 loc) · 810 Bytes

92. Reverse Linked List II

Solution 1 (O(n))

# 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
        """
        dummy = ListNode(-1)
        dummy.next = head
        p = dummy
        for _ in range(m - 1):
            p = p.next
        prev = p.next
        curr = prev.next
        for _ in range(n - m):
            t = curr.next
            curr.next = prev
            prev = curr
            curr = t
        p.next.next = curr
        p.next = prev
        return dummy.next