Simple Golang solution


  • 0
    D

    idea is simple, traverse list to the mth node, then use two pointer p1 and p2 to reverse the nodes in [m,n].

    func reverseBetween(head *ListNode, m int, n int) *ListNode {
        if m == n {
            return head
        }
        //pHead is a stub node
        pHead := new(ListNode)
        pHead.Next = head
        start := pHead
        i := 0
        for ;i<m-1;i++ {
            start = start.Next
        }
        
        p1,p2 := start.Next,start.Next.Next
        
        for ;i<n-1;i++ {
            p1.Next = p2.Next
            p2.Next = start.Next
            start.Next = p2
            p2 = p1.Next
        }
        return pHead.Next
    }
    

Log in to reply
 

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