Python one pass iterative solution

  • 21

    The idea is simple and intuitive: find linkedlist [m, n], reverse it, then connect m with n+1, connect n with m-1

    class Solution:
        # @param head, a ListNode
        # @param m, an integer
        # @param n, an integer
        # @return a ListNode
        def reverseBetween(self, head, m, n):
            if m == n:
                return head
            dummyNode = ListNode(0)
   = head
            pre = dummyNode
            for i in range(m - 1):
                pre =
            # reverse the [m, n] nodes
            reverse = None
            cur =
            for i in range(n - m + 1):
                next =
       = reverse
                reverse = cur
                cur = next
   = cur
   = reverse

  • 0
    This post is deleted!

  • 0

    what is

  • 0

    @IWantToPass refers to the end of the reversed list (first prev = None), links it to the latter part of the none reversed list.(1-->2, 2-->5)

Log in to reply

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