My Python solution - 36ms


  • 0
    Y

    Move slow to position m first and move fast to position n, swap them. Then move slow to the next until it reaches the middle of the list.

    # 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
            """
            mid = (m+n)/2
    
            slow = ListNode(0)
            slow.next = head
            # move slow to position m
            countslow = 0
            while countslow!=m:
                slow = slow.next
                countslow+=1
            
            # reversion
            while countslow<=mid:
                fast = slow
                d = n - m
                countfast = 0
                while countfast!=d:
                    fast = fast.next
                    countfast += 1
    
                slow.val, fast.val = fast.val, slow.val
                
                slow = slow.next
                m += 1
                n -= 1
                countslow+=1
            return head
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.