Swift solution - Iterative, Recursive


  • 0
    class Solution {
        func deleteDuplicates(_ head: ListNode?) -> ListNode? {
            var cur: ListNode? = head
            
            while cur != nil {
                if cur?.next == nil {
                    break
                }
                if cur?.val == cur?.next?.val {
                    cur?.next = cur?.next?.next
                } else {
                    cur = cur?.next
                }
            }
            
            return head
        }
        
        func deleteDuplicates_Recursive(_ head: ListNode?) -> ListNode? {
            if head == nil || head?.next == nil {
                return head
            }
            
            head?.next = deleteDuplicates_Recursive(head?.next)
            
            return head?.val == head?.next?.val ? head?.next : head
        }
    }
    

Log in to reply
 

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