Swift solution - Two Pointers


  • 0
    class Solution {
        func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
            let dummy = ListNode(0)
            var slow: ListNode? = dummy
            var fast: ListNode? = dummy
            
            slow?.next = head
            for _ in 1...(n + 1) {
                fast = fast?.next
            }
            while fast != nil {
                slow = slow?.next
                fast = fast?.next
            }
            slow?.next = slow?.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.