Skip to content

Instantly share code, notes, and snippets.

@naveensrinivasan
Created June 27, 2021 14:38
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 naveensrinivasan/15decfd156f0b90a9b593061a8f512f3 to your computer and use it in GitHub Desktop.
Save naveensrinivasan/15decfd156f0b90a9b593061a8f512f3 to your computer and use it in GitHub Desktop.
func removeNthFromEnd(head *ListNode, n int) *ListNode {
cur,cur2,counter:= head,head,0
if head == nil{
return head
}
for cur!= nil && cur.Next != nil{
counter+=2
cur = cur.Next.Next
}
if counter == 1{
return nil
}
if cur != nil{
counter++
}
pos := counter -n
prev := cur2
for cur2!= nil{
if pos == 0{
if prev == cur2{
return prev.Next
}
prev.Next = cur2.Next
break
}
pos--
prev = cur2
cur2 = cur2.Next
}
return head
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment