My Swift solution - Iterative & Recursive


  • 0
    class Solution {
        func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? {
            if head == nil || k == 1 {
                return head
            }
            
            let dummy = ListNode(0)
            var count = 0
            var current: ListNode? = dummy
            var next: ListNode? = dummy
            var prev: ListNode? = dummy
            
            dummy.next = head
            current = current?.next
            while current != nil {
                count += 1
                current = current?.next
            }
            while count >= k {
                current = prev?.next
                next = current?.next
                for _ in 1..<k {
                    current?.next = next?.next
                    next?.next = prev?.next
                    prev?.next = next
                    next = current?.next
                }
                prev = current
                count -= k
            }
            
            return dummy.next
        }
        
        func reverseKGroup_Rec(_ head: ListNode?, _ k: Int) -> ListNode? {
            var head = head
            var current = head
            var count = 0
            
            while current != nil && count != k {
                current = current?.next
                count += 1
            }
            if count == k {
                current = reverseKGroup_Rec(current, k)
                while count > 0 {
                    let temp = head?.next
                    head?.next = current
                    current = head
                    head = temp
                    count -= 1
                }
                head = current
            }
            
            return head
        }
    }
    

Log in to reply
 

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