My Swift solution - Iterative & Recursive


  • 0
    class Solution {
        func swapPairs(_ head: ListNode?) -> ListNode? {
            let dummy = ListNode(0)
            var head = head
            
            dummy.next = head
            head = dummy
            while head?.next?.next != nil {
                let n1 = head?.next
                let n2 = head?.next?.next
                head?.next = n2
                n1?.next = n2?.next
                n2?.next = n1
                head = n1
            }
            
            return dummy.next
        }
        
        func swapPairs_Rec(_ head: ListNode?) -> ListNode? {
            if  head?.next == nil {
                return head
            }
            
            let next = head?.next
            
            head?.next = swapPairs_Rec(head?.next?.next)
            next?.next = head
            
            return next
        }
    }
    

Log in to reply
 

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