Skip to content

Instantly share code, notes, and snippets.

@abdulrahmanAlotaibi
Created December 15, 2022 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdulrahmanAlotaibi/925855307d1887254fff1e11e28d6cfb to your computer and use it in GitHub Desktop.
Save abdulrahmanAlotaibi/925855307d1887254fff1e11e28d6cfb to your computer and use it in GitHub Desktop.
Linkedlist: Remove Nth Node From End of List
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummy := &ListNode{}
dummy.Next = head
first := head
var length int
for first != nil {
length++
first = first.Next
}
length -= n
first = dummy
// Stop before the node we want to delete
for length > 0 {
first = first.Next
length--
}
first.Next = first.Next.Next
return dummy.Next
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment