Swift solution


  • 0
    class Solution {
        func reverseBetween(_ head: ListNode?, _ m: Int, _ n: Int) -> ListNode? {
            if head == nil {
                return nil
            }
            
            let dummy = ListNode(0)
            dummy.next = head
            
            var pre: ListNode? = dummy
            for _ in 0..<(m - 1) {
                pre = pre?.next
            }
            
            let start: ListNode? = pre?.next
            var end: ListNode? = start?.next
            for _ in 0..<(n - m) {
                start?.next = end?.next
                end?.next = pre?.next
                pre?.next = end
                end = start?.next
            }
            
            return dummy.next
        }
    }
    

Log in to reply
 

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