Swift solution - Two Pointers


  • 0
    class Solution61 {
        func rotateRight(_ head: ListNode?, _ k: Int) -> ListNode? {
            if head == nil || head?.next == nil {
                return head
            }
            
            let dummy = ListNode(0)
            var fast: ListNode? = dummy
            var slow: ListNode? = dummy
            var i = 0
            dummy.next = head
    
            while fast?.next != nil {
                fast = fast?.next
                i += 1
            }
            for _ in stride(from: (i - k % i), to: 0, by: -1) {
                slow = slow?.next
            }
            fast?.next = dummy.next
            dummy.next = slow?.next
            slow?.next = nil
            
            return dummy.next
        }
    }
    

Log in to reply
 

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