Swift solution - Iterative, Recursive


  • 0
    class Solution {
        func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
            let dummy = ListNode(0)
            dummy.next = head
            var cur: ListNode? = head
            var pre: ListNode? = dummy
            
            while cur != nil {
                if cur?.val == val {
                    pre?.next = cur?.next
                } else {
                    pre = pre?.next
                }
                cur = cur?.next
            }
            
            return dummy.next
        }
        
        func removeElements_Recursive(_ head: ListNode?, _ val: Int) -> ListNode? {
            if head == nil {
                return nil
            }
            
            head?.next = removeElements_Recursive(head?.next, val)
            
            return head?.val == val ? head?.next : head
        }
    }
    

Log in to reply
 

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