Remove Nth Node From End of List

Solution in Go

func removeNthFromEnd(head *ListNode, n int) *ListNode {
    // Move the tail N positions
    tail := head
    for n > 0 {
        tail = tail.Next
        n--
    }

    // Now move tail to end, which would lead
    // the curr to "Len of List - N", which is the desired
    // node to be removed.
    var prev *ListNode
    curr := head
    for tail != nil {
        tail = tail.Next
        prev = curr
        curr = curr.Next
    }

    // Head needs to be removed
    if prev == nil {
        return head.Next
    }

    // Remove the required node from list
    prev.Next = prev.Next.Next

    return head
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.