Remove Nth Node From End of LinkedList

[Question]: Given the head of a linked list, remove the nth node from the end of the list and return its head.

Input: head = [1,2,3,4,5], n = 4
Output: [1,3,4,5]
#Approach Two pointer

Step: 1 Move fast pointer till count
Step: 2 Increment fast pointer till we get fast?.next == nil if we got nil just remove mid pointer…

func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
    var fast = head
    var slow = head
    var count = n
    
    while count > 0 {
        count -= 1
        fast = fast?.next
    }
    if fast == nil { return head?.next }
    
    while slow != nil && fast != nil {
        if fast?.next == nil {
            slow?.next = slow?.next?.next
        }
        slow = slow?.next
        fast = fast?.next
    }
    
    return head
}

var aLinkList2 =  ListNode(1, ListNode(2, ListNode(3,ListNode(4, ListNode(5)))))
let afterDeletingLL = removeNthFromEnd(aLinkList2, 2)// Remove second last
print("removeNthFromEnd------", afterDeletingLL) //  1 -> 2 -> 3 -> 5

Leave a Comment

Your email address will not be published. Required fields are marked *