Accepted Python solution. In place and in one-pass.


  • 0
    X

    Below is my solution. Any comments?

    class Solution:
        # @param head, a ListNode
        # @param m, an integer
        # @param n, an integer
        # @return a ListNode
        def reverseBetween(self, head, m, n):
            if head.next == None:
                return head
            dummyhead = ListNode(0)
            dummyhead.next = head
            prev = dummyhead
            for i in range(m-1):
                prev = prev.next
            one = prev.next
            two = one.next
            first = prev.next
            for i in range(0, n-m):
                rest = two.next
                prev.next = two
                two.next = one
                first.next = rest
                one = two
                two = rest
            return dummyhead.next

Log in to reply
 

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