Ruby solution


  • 0
    S
    def reverse_between(head, m, n)
        if m == 1
            return reverse(head, n - m + 1)
        else
            p = head
            (m-2).times { p = p.next }
            p.next = reverse(p.next, n-m+1)
            return head
        end 
    end
    
    def reverse(head, c)
        pre = head
        c.times { pre = pre.next }
        current = head
        c.times do
            tmp = current.next
            current.next = pre 
            pre = current
            current = tmp 
        end 
        pre 
    end
    

Log in to reply
 

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