Swift solution - Two Pointers, Recursive


  • 0
    class Solution {
        func deleteDuplicates(_ head: ListNode?) -> ListNode? {
            let dummy = ListNode(0)
            var fast: ListNode? = head
            var slow: ListNode? = dummy
            slow?.next = fast
            
            while fast != nil {
                while fast?.next != nil && fast?.val == fast?.next?.val {
                    fast = fast?.next
                }
                if slow?.next !== fast {
                    slow?.next = fast?.next
                    fast = slow?.next
                } else {
                    slow = slow?.next
                    fast = fast?.next
                }
            }
            
            return dummy.next
        }
        
        func deleteDuplicates_Recursive(_ head: ListNode?) -> ListNode? {
            if head == nil {
                return nil
            }
            
            var head = head
            
            if head?.next != nil && head?.val == head?.next?.val {
                while head?.next != nil && head?.val == head?.next?.val {
                    head = head?.next
                }
                return deleteDuplicates(head?.next)
            } else {
                head?.next = deleteDuplicates(head?.next)
            }
            
            return head
        }
    }
    

Log in to reply
 

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