Created
June 27, 2021 14:38
-
-
Save naveensrinivasan/15decfd156f0b90a9b593061a8f512f3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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