Swift 3 one and two pass solutions


  • 0
    Y
    class Solution {
        // One pass
        func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
            var dummy = ListNode(0) 
            dummy.next = head
            var fast = head
            var slow: ListNode? = dummy
            
            // move fast to be n nodes ahead of slow
            for _ in 0..<n {
                fast = fast?.next
            }
            
            // move fast to the end, slow n ahead of fast
            while fast != nil {
                fast = fast?.next
                slow = slow?.next
            }
            slow?.next = slow?.next?.next
            return dummy.next
        }
        
        
        // Two pass
        func removeNthFromEnd2Pass(_ head: ListNode?, _ n: Int) -> ListNode? {
            var dummy = ListNode(0)
            dummy.next = head
            var node = head
            // find the length of the linkedlist
            var length = 0
            while node != nil {
                node = node?.next
                length += 1
            }
            
            length = length - n
            node = dummy
            while length > 0 {
                node = node?.next
                length -= 1
            }
            node?.next = node?.next?.next
            return dummy.next
        }
    }
    
    
    

Log in to reply
 

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